<!DOCTYPE html>
<html lang="en">
<head>
  <title>Writing HTTP servers and clients - Vert.x</title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">
  <meta content="Vert.x is a tool-kit for building reactive applications on the JVM." name="description">
  <link href="http://vertx.io/stylesheets/docs.css" media="screen" rel="stylesheet">
  <link href="http://vertx.io/stylesheets/font-awesome.min.css" media="screen" rel="stylesheet">
  <link href="http://vertx.io/javascripts/styles/rainbow.min.css" media="screen" rel="stylesheet">
  <!-- IE 6-8 support of HTML 5 elements -->
  <!--[if lt IE 9]>
  <script src="http://static.jboss.org/theme/js/libs/html5/pre3.6/html5.min.js"></script>
  <![endif]-->

  <link rel="apple-touch-icon" sizes="57x57" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-57x57.png">
  <link rel="apple-touch-icon" sizes="60x60" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-60x60.png">
  <link rel="apple-touch-icon" sizes="72x72" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="76x76" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-76x76.png">
  <link rel="apple-touch-icon" sizes="114x114" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-114x114.png">
  <link rel="apple-touch-icon" sizes="120x120" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-120x120.png">
  <link rel="apple-touch-icon" sizes="144x144" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-144x144.png">
  <link rel="apple-touch-icon" sizes="152x152" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-152x152.png">
  <link rel="apple-touch-icon" sizes="180x180" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-180x180.png">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/favicon-32x32.png" sizes="32x32">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/android-chrome-192x192.png" sizes="192x192">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/favicon-96x96.png" sizes="96x96">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/favicon-16x16.png" sizes="16x16">
  <link rel="manifest" href="http://vertx.io/assets/favicons/vertx-favicon-7/manifest.json">
  <link rel="mask-icon" href="http://vertx.io/assets/favicons/vertx-favicon-7/safari-pinned-tab.svg" color="#5bbad5">
  <meta name="msapplication-TileColor" content="#7d3194">
  <meta name="msapplication-TileImage" content="http://vertx.io/assets/favicons/vertx-favicon-7/mstile-144x144.png">
  <meta name="theme-color" content="#ffffff">

  <link href="http://fonts.googleapis.com/css?family=Ubuntu:400,500,700,400italic" rel="stylesheet" type="text/css">
  <link rel="alternate" type="application/rss+xml" title="RSS"
     href="http://vertx.io/feed.xml">
  <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
    ga('create', 'UA-30144458-1', 'auto');
    ga('create', 'UA-71153120-1', 'auto', 'tracker');
    ga('send', 'pageview');
    ga('tracker.send', 'pageview');
  </script>
</head>
<body>

<a href="http://www.reactivemanifesto.org/" id="reactive-manifesto-banner">
  <img style="border: 0; position: fixed; right: 0; top:0; z-index: 9000"
    src="http://d379ifj7s9wntv.cloudfront.net/reactivemanifesto/images/ribbons/we-are-reactive-black-right.png">
</a>

<a id="skippy" class="sr-only sr-only-focusable" href="#content"><div class="container"><span class="skiplink-text">Skip to main content</span></div></a>

<header class="navbar navbar-default navbar-static-top" id="top" role="banner">
  <div class="container">
    <div class="navbar-header">
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#vertx-navbar-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a href="http://vertx.io/" class="navbar-brand"><img alt="Brand" src="http://vertx.io/assets/logo-sm.png"></a>
    </div>
    <nav class="collapse navbar-collapse" id="vertx-navbar-collapse">
      <ul class="nav navbar-nav navbar-right">
        <li><a href="http://vertx.io/download/">Download</a></li>
        <li><a href="http://vertx.io/docs/">Documentation</a></li>
        <li><a href="https://github.com/vert-x3/wiki/wiki">Wiki</a></li>
        <li><a href="http://vertx.io/community/">Community</a></li>
        <li><a href="http://vertx.io/materials/">Materials</a></li>
        <li><a href="http://vertx.io/blog/">Blog</a></li>        
      </ul>
    </nav>
  </div>
</header>



  <div class="page-header" id="content">
    <div class="container">
      <div class="row">
        <div class="col-sm-12">
          <h1>Writing HTTP servers and clients</h1>
          
        </div>
      </div>
    </div>
  </div>




<div id="content">
  <div class="container docs-content">
    <div class="row">
      <div class="col-sm-12 col-md-push-9 col-md-3 hidden-xs hidden-sm">
        <div id="sidebar" data-spy="affix">
          <ul class="sectlevel1">
<li><a href="#_writing_http_servers_and_clients">Writing HTTP servers and clients</a>
<ul class="sectlevel2">
<li><a href="#_creating_an_http_server">Creating an HTTP Server</a></li>
<li><a href="#_configuring_an_http_server">Configuring an HTTP server</a></li>
<li><a href="#_configuring_an_http_2_server">Configuring an HTTP/2 server</a></li>
<li><a href="#_logging_network_server_activity">Logging network server activity</a></li>
<li><a href="#_start_the_server_listening">Start the Server Listening</a></li>
<li><a href="#_getting_notified_of_incoming_requests">Getting notified of incoming requests</a></li>
<li><a href="#_handling_requests">Handling requests</a></li>
<li><a href="#_sending_back_responses">Sending back responses</a></li>
<li><a href="#_http_compression">HTTP Compression</a></li>
<li><a href="#_creating_an_http_client">Creating an HTTP client</a></li>
<li><a href="#_logging_network_client_activity">Logging network client activity</a></li>
<li><a href="#_making_requests">Making requests</a></li>
<li><a href="#_handling_http_responses">Handling http responses</a></li>
<li><a href="#_enabling_compression_on_the_client">Enabling compression on the client</a></li>
<li><a href="#_http_1_x_pooling_and_keep_alive">HTTP/1.x pooling and keep alive</a></li>
<li><a href="#_http_1_1_pipe_lining">HTTP/1.1 pipe-lining</a></li>
<li><a href="#_http_2_multiplexing">HTTP/2 multiplexing</a></li>
<li><a href="#_http_connections">HTTP connections</a></li>
<li><a href="#_httpclient_usage">HttpClient usage</a></li>
<li><a href="#_server_sharing">Server sharing</a></li>
<li><a href="#_using_https_with_vert_x">Using HTTPS with Vert.x</a></li>
<li><a href="#_websockets">WebSockets</a></li>
<li><a href="#_using_a_proxy_for_http_https_connections">Using a proxy for HTTP/HTTPS connections</a></li>
<li><a href="#_automatic_clean_up_in_verticles">Automatic clean-up in verticles</a></li>
</ul>
</li>
</ul>
        </div>
      </div>
      <div class="col-sm-12 col-md-pull-3 col-md-9">
        <div class="toc hidden-md hidden-lg">
          <h2>Table of Contents</h2>
          <ul class="sectlevel1">
<li><a href="#_writing_http_servers_and_clients">Writing HTTP servers and clients</a>
<ul class="sectlevel2">
<li><a href="#_creating_an_http_server">Creating an HTTP Server</a></li>
<li><a href="#_configuring_an_http_server">Configuring an HTTP server</a></li>
<li><a href="#_configuring_an_http_2_server">Configuring an HTTP/2 server</a></li>
<li><a href="#_logging_network_server_activity">Logging network server activity</a></li>
<li><a href="#_start_the_server_listening">Start the Server Listening</a></li>
<li><a href="#_getting_notified_of_incoming_requests">Getting notified of incoming requests</a></li>
<li><a href="#_handling_requests">Handling requests</a></li>
<li><a href="#_sending_back_responses">Sending back responses</a></li>
<li><a href="#_http_compression">HTTP Compression</a></li>
<li><a href="#_creating_an_http_client">Creating an HTTP client</a></li>
<li><a href="#_logging_network_client_activity">Logging network client activity</a></li>
<li><a href="#_making_requests">Making requests</a></li>
<li><a href="#_handling_http_responses">Handling http responses</a></li>
<li><a href="#_enabling_compression_on_the_client">Enabling compression on the client</a></li>
<li><a href="#_http_1_x_pooling_and_keep_alive">HTTP/1.x pooling and keep alive</a></li>
<li><a href="#_http_1_1_pipe_lining">HTTP/1.1 pipe-lining</a></li>
<li><a href="#_http_2_multiplexing">HTTP/2 multiplexing</a></li>
<li><a href="#_http_connections">HTTP connections</a></li>
<li><a href="#_httpclient_usage">HttpClient usage</a></li>
<li><a href="#_server_sharing">Server sharing</a></li>
<li><a href="#_using_https_with_vert_x">Using HTTPS with Vert.x</a></li>
<li><a href="#_websockets">WebSockets</a></li>
<li><a href="#_using_a_proxy_for_http_https_connections">Using a proxy for HTTP/HTTPS connections</a></li>
<li><a href="#_automatic_clean_up_in_verticles">Automatic clean-up in verticles</a></li>
</ul>
</li>
</ul>
        </div>
        <div class="sect1">
<h2 id="_writing_http_servers_and_clients">Writing HTTP servers and clients</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Vert.x allows you to easily write non blocking HTTP clients and servers.</p>
</div>
<div class="paragraph">
<p>Vert.x supports the HTTP/1.0, HTTP/1.1 and HTTP/2 protocols.</p>
</div>
<div class="paragraph">
<p>The base API for HTTP is the same for HTTP/1.x and HTTP/2, specific API features are available for dealing with the
HTTP/2 protocol.</p>
</div>
<div class="sect2">
<h3 id="_creating_an_http_server">Creating an HTTP Server</h3>
<div class="paragraph">
<p>The simplest way to create an HTTP server, using all default options is as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value server = vertx.createHttpServer();</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_configuring_an_http_server">Configuring an HTTP server</h3>
<div class="paragraph">
<p>If you don&#8217;t want the default, a server can be configured by passing in a <code><a href="../../ceylondoc/vertx-core//http/HttpServerOptions.type.html">HttpServerOptions</a></code>
instance when creating it:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value options = HttpServerOptions {
  maxWebsocketFrameSize = 1000000;
};

value server = vertx.createHttpServer(options);</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_configuring_an_http_2_server">Configuring an HTTP/2 server</h3>
<div class="paragraph">
<p>Vert.x supports HTTP/2 over TLS <code>h2</code> and over TCP <code>h2c</code>.</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>h2</code> identifies the HTTP/2 protocol when used over TLS negotiated by <a href="https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation">Application-Layer Protocol Negotiation</a> (ALPN)</p>
</li>
<li>
<p><code>h2c</code> identifies the HTTP/2 protocol when using in clear text over TCP, such connections are established either with
an HTTP/1.1 upgraded request or directly</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>To handle <code>h2</code> requests, TLS must be enabled along with <code><a href="../../ceylondoc/vertx-core//http/HttpServerOptions.type.html#setUseAlpn(boolean)">useAlpn</a></code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value options = HttpServerOptions {
  useAlpn = true;
  ssl = true;
  keyStoreOptions = JksOptions {
    path = "/path/to/my/keystore";
  };
};

value server = vertx.createHttpServer(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>ALPN is a TLS extension that negotiates the protocol before the client and the server start to exchange data.</p>
</div>
<div class="paragraph">
<p>Clients that don&#8217;t support ALPN will still be able to do a <em>classic</em> SSL handshake.</p>
</div>
<div class="paragraph">
<p>ALPN will usually agree on the <code>h2</code> protocol, although <code>http/1.1</code> can be used if the server or the client decides
so.</p>
</div>
<div class="paragraph">
<p>To handle <code>h2c</code> requests, TLS must be disabled, the server will upgrade to HTTP/2 any request HTTP/1.1 that wants to
upgrade to HTTP/2. It will also accept a direct <code>h2c</code> connection beginning with the <code>PRI * HTTP/2.0\r\nSM\r\n</code> preface.</p>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<div class="title">Warning</div>
</td>
<td class="content">
most browsers won&#8217;t support <code>h2c</code>, so for serving web sites you should use <code>h2</code> and not <code>h2c</code>.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>When a server accepts an HTTP/2 connection, it sends to the client its <code><a href="../../ceylondoc/vertx-core//http/HttpServerOptions.type.html#getInitialSettings()">initial settings</a></code>.
The settings define how the client can use the connection, the default initial settings for a server are:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code><a href="../../ceylondoc/vertx-core//http/Http2Settings.type.html#getMaxConcurrentStreams()">getMaxConcurrentStreams</a></code>: <code>100</code> as recommended by the HTTP/2 RFC</p>
</li>
<li>
<p>the default HTTP/2 settings values for the others</p>
</li>
</ul>
</div>
</div>
<div class="sect2">
<h3 id="_logging_network_server_activity">Logging network server activity</h3>
<div class="paragraph">
<p>For debugging purposes, network activity can be logged.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value options = HttpServerOptions {
  logActivity = true;
};

value server = vertx.createHttpServer(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>See the chapter on <a href="#logging_network_activity">logging network activity</a> for a detailed explanation.</p>
</div>
</div>
<div class="sect2">
<h3 id="_start_the_server_listening">Start the Server Listening</h3>
<div class="paragraph">
<p>To tell the server to listen for incoming requests you use one of the <code><a href="../../ceylondoc/vertx-core//http/HttpServer.type.html#listen()">listen</a></code>
alternatives.</p>
</div>
<div class="paragraph">
<p>To tell the server to listen at the host and port as specified in the options:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value server = vertx.createHttpServer();
server.listen();</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or to specify the host and port in the call to listen, ignoring what is configured in the options:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value server = vertx.createHttpServer();
server.listen(8080, "myhost.com");</code></pre>
</div>
</div>
<div class="paragraph">
<p>The default host is <code>0.0.0.0</code> which means 'listen on all available addresses' and the default port is <code>80</code>.</p>
</div>
<div class="paragraph">
<p>The actual bind is asynchronous so the server might not actually be listening until some time <strong>after</strong> the call to
listen has returned.</p>
</div>
<div class="paragraph">
<p>If you want to be notified when the server is actually listening you can provide a handler to the <code>listen</code> call.
For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value server = vertx.createHttpServer();
server.listen(8080, "myhost.com", (HttpServer|Throwable res) {
  if (is HttpServer res) {
    print("Server is now listening!");
  } else {
    print("Failed to bind!");
  };
});</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_getting_notified_of_incoming_requests">Getting notified of incoming requests</h3>
<div class="paragraph">
<p>To be notified when a request arrives you need to set a <code><a href="../../ceylondoc/vertx-core//http/HttpServer.type.html#requestHandler(io.vertx.core.Handler)">requestHandler</a></code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value server = vertx.createHttpServer();
server.requestHandler((HttpServerRequest request) {
  // Handle the request in here
});</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_handling_requests">Handling requests</h3>
<div class="paragraph">
<p>When a request arrives, the request handler is called passing in an instance of <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html">HttpServerRequest</a></code>.
This object represents the server side HTTP request.</p>
</div>
<div class="paragraph">
<p>The handler is called when the headers of the request have been fully read.</p>
</div>
<div class="paragraph">
<p>If the request contains a body, that body will arrive at the server some time after the request handler has been called.</p>
</div>
<div class="paragraph">
<p>The server request object allows you to retrieve the <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#uri()">uri</a></code>,
<code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#path()">path</a></code>, <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#params()">params</a></code> and
<code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#headers()">headers</a></code>, amongst other things.</p>
</div>
<div class="paragraph">
<p>Each server request object is associated with one server response object. You use
<code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#response()">response</a></code> to get a reference to the <code><a href="../../ceylondoc/vertx-core//http/HttpServerResponse.type.html">HttpServerResponse</a></code>
object.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s a simple example of a server handling a request and replying with "hello world" to it.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">vertx.createHttpServer().requestHandler((HttpServerRequest request) {
  request.response().end("Hello world");
}).listen(8080);</code></pre>
</div>
</div>
<div class="sect3">
<h4 id="_request_version">Request version</h4>
<div class="paragraph">
<p>The version of HTTP specified in the request can be retrieved with <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#version()">version</a></code></p>
</div>
</div>
<div class="sect3">
<h4 id="_request_method">Request method</h4>
<div class="paragraph">
<p>Use <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#method()">method</a></code> to retrieve the HTTP method of the request.
(i.e. whether it&#8217;s GET, POST, PUT, DELETE, HEAD, OPTIONS, etc).</p>
</div>
</div>
<div class="sect3">
<h4 id="_request_uri">Request URI</h4>
<div class="paragraph">
<p>Use <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#uri()">uri</a></code> to retrieve the URI of the request.</p>
</div>
<div class="paragraph">
<p>Note that this is the actual URI as passed in the HTTP request, and it&#8217;s almost always a relative URI.</p>
</div>
<div class="paragraph">
<p>The URI is as defined in <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html">Section 5.1.2 of the HTTP specification - Request-URI</a></p>
</div>
</div>
<div class="sect3">
<h4 id="_request_path">Request path</h4>
<div class="paragraph">
<p>Use <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#path()">path</a></code> to return the path part of the URI</p>
</div>
<div class="paragraph">
<p>For example, if the request URI was:</p>
</div>
<div class="literalblock">
<div class="content">
<pre>a/b/c/page.html?param1=abc&amp;param2=xyz</pre>
</div>
</div>
<div class="paragraph">
<p>Then the path would be</p>
</div>
<div class="literalblock">
<div class="content">
<pre>/a/b/c/page.html</pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_request_query">Request query</h4>
<div class="paragraph">
<p>Use <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#query()">query</a></code> to return the query part of the URI</p>
</div>
<div class="paragraph">
<p>For example, if the request URI was:</p>
</div>
<div class="literalblock">
<div class="content">
<pre>a/b/c/page.html?param1=abc&amp;param2=xyz</pre>
</div>
</div>
<div class="paragraph">
<p>Then the query would be</p>
</div>
<div class="literalblock">
<div class="content">
<pre>param1=abc&amp;param2=xyz</pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_request_headers">Request headers</h4>
<div class="paragraph">
<p>Use <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#headers()">headers</a></code> to return the headers of the HTTP request.</p>
</div>
<div class="paragraph">
<p>This returns an instance of <code><a href="../../ceylondoc/vertx-core//MultiMap.type.html">MultiMap</a></code> - which is like a normal Map or Hash but allows multiple
values for the same key - this is because HTTP allows multiple header values with the same key.</p>
</div>
<div class="paragraph">
<p>It also has case-insensitive keys, that means you can do the following:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value headers = request.headers();

// Get the User-Agent:
print("User agent is ``headers.get("user-agent")``");

// You can also do this and get the same result:
print("User agent is ``headers.get("User-Agent")``");</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_request_host">Request host</h4>
<div class="paragraph">
<p>Use <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#host()">host</a></code> to return the host of the HTTP request.</p>
</div>
<div class="paragraph">
<p>For HTTP/1.x requests the <code>host</code> header is returned, for HTTP/1 requests the <code>:authority</code> pseudo header is returned.</p>
</div>
</div>
<div class="sect3">
<h4 id="_request_parameters">Request parameters</h4>
<div class="paragraph">
<p>Use <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#params()">params</a></code> to return the parameters of the HTTP request.</p>
</div>
<div class="paragraph">
<p>Just like <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#headers()">headers</a></code> this returns an instance of <code><a href="../../ceylondoc/vertx-core//MultiMap.type.html">MultiMap</a></code>
as there can be more than one parameter with the same name.</p>
</div>
<div class="paragraph">
<p>Request parameters are sent on the request URI, after the path. For example if the URI was:</p>
</div>
<div class="literalblock">
<div class="content">
<pre>/page.html?param1=abc&amp;param2=xyz</pre>
</div>
</div>
<div class="paragraph">
<p>Then the parameters would contain the following:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>param1: 'abc'
param2: 'xyz</pre>
</div>
</div>
<div class="paragraph">
<p>Note that these request parameters are retrieved from the URL of the request. If you have form attributes that
have been sent as part of the submission of an HTML form submitted in the body of a <code>multi-part/form-data</code> request
then they will not appear in the params here.</p>
</div>
</div>
<div class="sect3">
<h4 id="_remote_address">Remote address</h4>
<div class="paragraph">
<p>The address of the sender of the request can be retrieved with <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#remoteAddress()">remoteAddress</a></code>.</p>
</div>
</div>
<div class="sect3">
<h4 id="_absolute_uri">Absolute URI</h4>
<div class="paragraph">
<p>The URI passed in an HTTP request is usually relative. If you wish to retrieve the absolute URI corresponding
to the request, you can get it with <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#absoluteURI()">absoluteURI</a></code></p>
</div>
</div>
<div class="sect3">
<h4 id="_end_handler">End handler</h4>
<div class="paragraph">
<p>The <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#endHandler(io.vertx.core.Handler)">endHandler</a></code> of the request is invoked when the entire request,
including any body has been fully read.</p>
</div>
</div>
<div class="sect3">
<h4 id="_reading_data_from_the_request_body">Reading Data from the Request Body</h4>
<div class="paragraph">
<p>Often an HTTP request contains a body that we want to read. As previously mentioned the request handler is called
when just the headers of the request have arrived so the request object does not have a body at that point.</p>
</div>
<div class="paragraph">
<p>This is because the body may be very large (e.g. a file upload) and we don&#8217;t generally want to buffer the entire
body in memory before handing it to you, as that could cause the server to exhaust available memory.</p>
</div>
<div class="paragraph">
<p>To receive the body, you can use the <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#handler(io.vertx.core.Handler)">handler</a></code>  on the request,
this will get called every time a chunk of the request body arrives. Here&#8217;s an example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">request.handler((Buffer buffer) {
  print("I have received a chunk of the body of length ``buffer.length()``");
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>The object passed into the handler is a <code><a href="../../ceylondoc/vertx-core//buffer/Buffer.type.html">Buffer</a></code>, and the handler can be called
multiple times as data arrives from the network, depending on the size of the body.</p>
</div>
<div class="paragraph">
<p>In some cases (e.g. if the body is small) you will want to aggregate the entire body in memory, so you could do
the aggregation yourself as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">import io.vertx.ceylon.core.buffer { buffer }

...


// Create an empty buffer
value totalBuffer = buffer.buffer();

request.handler((Buffer buffer) {
  print("I have received a chunk of the body of length ``buffer.length()``");
  totalBuffer.appendBuffer(buffer);
});

request.endHandler(() {
  print("Full body received, length = ``totalBuffer.length()``");
});</code></pre>
</div>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1">This is such a common case, that Vert.x provides a `link:../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#bodyHandler((@io.vertx.codegen.annotations.Nullable </dt>
<dd>
<p>io.vertx.core.Handler))[bodyHandler]` to do this
for you. The body handler is called once when all the body has been received:</p>
</dd>
</dl>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">request.bodyHandler((Buffer totalBuffer) {
  print("Full body received, length = ``totalBuffer.length()``");
});</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_pumping_requests">Pumping requests</h4>
<div class="paragraph">
<p>The request object is a <code><a href="../../ceylondoc/vertx-core//streams/ReadStream.type.html">ReadStream</a></code> so you can pump the request body to any
<code><a href="../../ceylondoc/vertx-core//streams/WriteStream.type.html">WriteStream</a></code> instance.</p>
</div>
<div class="paragraph">
<p>See the chapter on <a href="#streams">streams and pumps</a> for a detailed explanation.</p>
</div>
</div>
<div class="sect3">
<h4 id="_handling_html_forms">Handling HTML forms</h4>
<div class="paragraph">
<p>HTML forms can be submitted with either a content type of <code>application/x-www-form-urlencoded</code> or <code>multipart/form-data</code>.</p>
</div>
<div class="paragraph">
<p>For url encoded forms, the form attributes are encoded in the url, just like normal query parameters.</p>
</div>
<div class="paragraph">
<p>For multi-part forms they are encoded in the request body, and as such are not available until the entire body
has been read from the wire.</p>
</div>
<div class="paragraph">
<p>Multi-part forms can also contain file uploads.</p>
</div>
<div class="paragraph">
<p>If you want to retrieve the attributes of a multi-part form you should tell Vert.x that you expect to receive
such a form <strong>before</strong> any of the body is read by calling <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#setExpectMultipart(boolean)">setExpectMultipart</a></code>
with true, and then you should retrieve the actual attributes using <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#formAttributes()">formAttributes</a></code>
once the entire body has been read:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">server.requestHandler((HttpServerRequest request) {
  request.setExpectMultipart(true);
  request.endHandler(() {
    // The body has now been fully read, so retrieve the form attributes
    value formAttributes = request.formAttributes();
  });
});</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_handling_form_file_uploads">Handling form file uploads</h4>
<div class="paragraph">
<p>Vert.x can also handle file uploads which are encoded in a multi-part request body.</p>
</div>
<div class="paragraph">
<p>To receive file uploads you tell Vert.x to expect a multi-part form and set an
<code>link:../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#uploadHandler@io.vertx.codegen.annotations.Nullable :: io.vertx.core.Handler[uploadHandler]</code> on the request.</p>
</div>
<div class="paragraph">
<p>This handler will be called once for every
upload that arrives on the server.</p>
</div>
<div class="paragraph">
<p>The object passed into the handler is a <code><a href="../../ceylondoc/vertx-core//http/HttpServerFileUpload.type.html">HttpServerFileUpload</a></code> instance.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">server.requestHandler((HttpServerRequest request) {
  request.setExpectMultipart(true);
  request.uploadHandler((HttpServerFileUpload upload) {
    print("Got a file upload ``upload.name()``");
  });
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>File uploads can be large we don&#8217;t provide the entire upload in a single buffer as that might result in memory
exhaustion, instead, the upload data is received in chunks:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">request.uploadHandler((HttpServerFileUpload upload) {
  upload.handler((Buffer chunk) {
    print("Received a chunk of the upload of length ``chunk.length()``");
  });
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>The upload object is a <code><a href="../../ceylondoc/vertx-core//streams/ReadStream.type.html">ReadStream</a></code> so you can pump the request body to any
<code><a href="../../ceylondoc/vertx-core//streams/WriteStream.type.html">WriteStream</a></code> instance. See the chapter on <a href="#streams">streams and pumps</a> for a
detailed explanation.</p>
</div>
<div class="paragraph">
<p>If you just want to upload the file to disk somewhere you can use <code><a href="../../ceylondoc/vertx-core//http/HttpServerFileUpload.type.html#streamToFileSystem(java.lang.String)">streamToFileSystem</a></code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">request.uploadHandler((HttpServerFileUpload upload) {
  upload.streamToFileSystem("myuploads_directory/``upload.filename()``");
});</code></pre>
</div>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<div class="title">Warning</div>
</td>
<td class="content">
Make sure you check the filename in a production system to avoid malicious clients uploading files
to arbitrary places on your filesystem. See <a href="#Security notes">security notes</a> for more information.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_receiving_custom_http_2_frames">Receiving custom HTTP/2 frames</h4>
<div class="paragraph">
<p>HTTP/2 is a framed protocol with various frames for the HTTP request/response model. The protocol allows other kind
of frames to be sent and received.</p>
</div>
<div class="paragraph">
<p>To receive custom frames, you can use the <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#customFrameHandler(io.vertx.core.Handler)">customFrameHandler</a></code> on the request,
this will get called every time a custom frame arrives. Here&#8217;s an example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">request.customFrameHandler((HttpFrame frame) {

  print("Received a frame type=``frame.type()`` payload``frame.payload().toString()``");
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>HTTP/2 frames are not subject to flow control - the frame handler will be called immediatly when a
custom frame is received whether the request is paused or is not</p>
</div>
</div>
<div class="sect3">
<h4 id="_non_standard_http_methods">Non standard HTTP methods</h4>
<div class="paragraph">
<p>The <code><a href="todo">OTHER</a></code> HTTP method is used for non standard methods, in this case
<code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#rawMethod()">rawMethod</a></code> returns the HTTP method as sent by the client.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_sending_back_responses">Sending back responses</h3>
<div class="paragraph">
<p>The server response object is an instance of <code><a href="../../ceylondoc/vertx-core//http/HttpServerResponse.type.html">HttpServerResponse</a></code> and is obtained from the
request with <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#response()">response</a></code>.</p>
</div>
<div class="paragraph">
<p>You use the response object to write a response back to the HTTP client.</p>
</div>
<div class="sect3">
<h4 id="_setting_status_code_and_message">Setting status code and message</h4>
<div class="paragraph">
<p>The default HTTP status code for a response is <code>200</code>, representing <code>OK</code>.</p>
</div>
<div class="paragraph">
<p>Use <code><a href="../../ceylondoc/vertx-core//http/HttpServerResponse.type.html#setStatusCode(int)">setStatusCode</a></code> to set a different code.</p>
</div>
<div class="paragraph">
<p>You can also specify a custom status message with <code><a href="../../ceylondoc/vertx-core//http/HttpServerResponse.type.html#setStatusMessage(java.lang.String)">setStatusMessage</a></code>.</p>
</div>
<div class="paragraph">
<p>If you don&#8217;t specify a status message, the default one corresponding to the status code will be used.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
for HTTP/2 the status won&#8217;t be present in the response since the protocol won&#8217;t transmit the message
to the client
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_writing_http_responses">Writing HTTP responses</h4>
<div class="paragraph">
<p>To write data to an HTTP response, you use one the <code><a href="../../ceylondoc/vertx-core//http/HttpServerResponse.type.html#write(io.vertx.core.buffer.Buffer)">write</a></code> operations.</p>
</div>
<div class="paragraph">
<p>These can be invoked multiple times before the response is ended. They can be invoked in a few ways:</p>
</div>
<div class="paragraph">
<p>With a single buffer:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value response = request.response();
response.write(buffer);</code></pre>
</div>
</div>
<div class="paragraph">
<p>With a string. In this case the string will encoded using UTF-8 and the result written to the wire.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value response = request.response();
response.write("hello world!");</code></pre>
</div>
</div>
<div class="paragraph">
<p>With a string and an encoding. In this case the string will encoded using the specified encoding and the
result written to the wire.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value response = request.response();
response.write("hello world!", "UTF-16");</code></pre>
</div>
</div>
<div class="paragraph">
<p>Writing to a response is asynchronous and always returns immediately after the write has been queued.</p>
</div>
<div class="paragraph">
<p>If you are just writing a single string or buffer to the HTTP response you can write it and end the response in a
single call to the <code><a href="../../ceylondoc/vertx-core//http/HttpServerResponse.type.html#end(java.lang.String)">end</a></code></p>
</div>
<div class="paragraph">
<p>The first call to write results in the response header being being written to the response. Consequently, if you are
not using HTTP chunking then you must set the <code>Content-Length</code> header before writing to the response, since it will
be too late otherwise. If you are using HTTP chunking you do not have to worry.</p>
</div>
</div>
<div class="sect3">
<h4 id="_ending_http_responses">Ending HTTP responses</h4>
<div class="paragraph">
<p>Once you have finished with the HTTP response you should <code><a href="../../ceylondoc/vertx-core//http/HttpServerResponse.type.html#end(java.lang.String)">end</a></code> it.</p>
</div>
<div class="paragraph">
<p>This can be done in several ways:</p>
</div>
<div class="paragraph">
<p>With no arguments, the response is simply ended.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value response = request.response();
response.write("hello world!");
response.end();</code></pre>
</div>
</div>
<div class="paragraph">
<p>It can also be called with a string or buffer in the same way <code>write</code> is called. In this case it&#8217;s just the same as
calling write with a string or buffer followed by calling end with no arguments. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value response = request.response();
response.end("hello world!");</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_closing_the_underlying_connection">Closing the underlying connection</h4>
<div class="paragraph">
<p>You can close the underlying TCP connection with <code><a href="../../ceylondoc/vertx-core//http/HttpServerResponse.type.html#close()">close</a></code>.</p>
</div>
<div class="paragraph">
<p>Non keep-alive connections will be automatically closed by Vert.x when the response is ended.</p>
</div>
<div class="paragraph">
<p>Keep-alive connections are not automatically closed by Vert.x by default. If you want keep-alive connections to be
closed after an idle time, then you configure <code><a href="../../ceylondoc/vertx-core//http/HttpServerOptions.type.html#setIdleTimeout(int)">idleTimeout</a></code>.</p>
</div>
<div class="paragraph">
<p>HTTP/2 connections send a <code>GOAWAY</code> frame before closing the response.</p>
</div>
</div>
<div class="sect3">
<h4 id="_setting_response_headers">Setting response headers</h4>
<div class="paragraph">
<p>HTTP response headers can be added to the response by adding them directly to the
<code><a href="../../ceylondoc/vertx-core//http/HttpServerResponse.type.html#headers()">headers</a></code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value response = request.response();
value headers = response.headers();
headers.set("content-type", "text/html");
headers.set("other-header", "wibble");</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or you can use <code><a href="../../ceylondoc/vertx-core//http/HttpServerResponse.type.html#putHeader(java.lang.String,%20java.lang.String)">putHeader</a></code></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value response = request.response();
response.putHeader("content-type", "text/html").putHeader("other-header", "wibble");</code></pre>
</div>
</div>
<div class="paragraph">
<p>Headers must all be added before any parts of the response body are written.</p>
</div>
</div>
<div class="sect3">
<h4 id="_chunked_http_responses_and_trailers">Chunked HTTP responses and trailers</h4>
<div class="paragraph">
<p>Vert.x supports <a href="http://en.wikipedia.org/wiki/Chunked_transfer_encoding">HTTP Chunked Transfer Encoding</a>.</p>
</div>
<div class="paragraph">
<p>This allows the HTTP response body to be written in chunks, and is normally used when a large response body is
being streamed to a client and the total size is not known in advance.</p>
</div>
<div class="paragraph">
<p>You put the HTTP response into chunked mode as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value response = request.response();
response.setChunked(true);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Default is non-chunked. When in chunked mode, each call to one of the <code><a href="../../ceylondoc/vertx-core//http/HttpServerResponse.type.html#write(io.vertx.core.buffer.Buffer)">write</a></code>
methods will result in a new HTTP chunk being written out.</p>
</div>
<div class="paragraph">
<p>When in chunked mode you can also write HTTP response trailers to the response. These are actually written in
the final chunk of the response.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
chunked response has no effect for an HTTP/2 stream
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>To add trailers to the response, add them directly to the <code><a href="../../ceylondoc/vertx-core//http/HttpServerResponse.type.html#trailers()">trailers</a></code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value response = request.response();
response.setChunked(true);
value trailers = response.trailers();
trailers.set("X-wibble", "woobble").set("X-quux", "flooble");</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or use <code><a href="../../ceylondoc/vertx-core//http/HttpServerResponse.type.html#putTrailer(java.lang.String,%20java.lang.String)">putTrailer</a></code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value response = request.response();
response.setChunked(true);
response.putTrailer("X-wibble", "woobble").putTrailer("X-quux", "flooble");</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_serving_files_directly_from_disk_or_the_classpath">Serving files directly from disk or the classpath</h4>
<div class="paragraph">
<p>If you were writing a web server, one way to serve a file from disk would be to open it as an <code><a href="../../ceylondoc/vertx-core//file/AsyncFile.type.html">AsyncFile</a></code>
and pump it to the HTTP response.</p>
</div>
<div class="paragraph">
<p>Or you could load it it one go using <code><a href="../../ceylondoc/vertx-core//file/FileSystem.type.html#readFile(java.lang.String,%20io.vertx.core.Handler)">readFile</a></code> and write it straight to the response.</p>
</div>
<div class="paragraph">
<p>Alternatively, Vert.x provides a method which allows you to serve a file from disk or the filesystem to an HTTP response
in one operation.
Where supported by the underlying operating system this may result in the OS directly transferring bytes from the
file to the socket without being copied through user-space at all.</p>
</div>
<div class="paragraph">
<p>This is done by using <code><a href="../../ceylondoc/vertx-core//http/HttpServerResponse.type.html#sendFile(java.lang.String)">sendFile</a></code>, and is usually more efficient for large
files, but may be slower for small files.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s a very simple web server that serves files from the file system using sendFile:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">vertx.createHttpServer().requestHandler((HttpServerRequest request) {
  value file = "";
  if (request.path() == "/") {
    file = "index.html";
  } else if (!request.path().contains("..")) {
    file = request.path();
  };
  request.response().sendFile("web/``file``");
}).listen(8080);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Sending a file is asynchronous and may not complete until some time after the call has returned. If you want to
be notified when the file has been writen you can use <code><a href="../../ceylondoc/vertx-core//http/HttpServerResponse.type.html#sendFile(java.lang.String,%20io.vertx.core.Handler)">sendFile</a></code></p>
</div>
<div class="paragraph">
<p>Please see the chapter about <a href="#classpath">serving files from the classpath</a> for restrictions about the classpath resolution or disabling it.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
If you use <code>sendFile</code> while using HTTPS it will copy through user-space, since if the kernel is copying data
directly from disk to socket it doesn&#8217;t give us an opportunity to apply any encryption.
</td>
</tr>
</table>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<div class="title">Warning</div>
</td>
<td class="content">
If you&#8217;re going to write web servers directly using Vert.x be careful that users cannot exploit the
path to access files outside the directory from which you want to serve them or the classpath It may be safer instead to use
Vert.x Web.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>When there is a need to serve just a segment of a file, say starting from a given byte, you can achieve this by doing:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">vertx.createHttpServer().requestHandler((HttpServerRequest request) {
  value offset = 0;
  try {
    offset = Long.parseLong(request.getParam("start"));
  } catch(Exception e) {
    // error handling...
  }

  value end = Long.MAX_VALUE;
  try {
    end = Long.parseLong(request.getParam("end"));
  } catch(Exception e) {
    // error handling...
  }

  request.response().sendFile("web/mybigfile.txt", offset, end);
}).listen(8080);</code></pre>
</div>
</div>
<div class="paragraph">
<p>You are not required to supply the length if you want to send a file starting from an offset until the end, in this
case you can just do:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">vertx.createHttpServer().requestHandler((HttpServerRequest request) {
  value offset = 0;
  try {
    offset = Long.parseLong(request.getParam("start"));
  } catch(Exception e) {
    // error handling...
  }

  request.response().sendFile("web/mybigfile.txt", offset);
}).listen(8080);</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_pumping_responses">Pumping responses</h4>
<div class="paragraph">
<p>The server response is a <code><a href="../../ceylondoc/vertx-core//streams/WriteStream.type.html">WriteStream</a></code> instance so you can pump to it from any
<code><a href="../../ceylondoc/vertx-core//streams/ReadStream.type.html">ReadStream</a></code>, e.g. <code><a href="../../ceylondoc/vertx-core//file/AsyncFile.type.html">AsyncFile</a></code>, <code><a href="../../ceylondoc/vertx-core//net/NetSocket.type.html">NetSocket</a></code>,
<code><a href="../../ceylondoc/vertx-core//http/WebSocket.type.html">WebSocket</a></code> or <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html">HttpServerRequest</a></code>.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s an example which echoes the request body back in the response for any PUT methods.
It uses a pump for the body, so it will work even if the HTTP request body is much larger than can fit in memory
at any one time:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">import io.vertx.ceylon.core.http { put }
import io.vertx.ceylon.core.streams { pump }

...

vertx.createHttpServer().requestHandler((HttpServerRequest request) {
  value response = request.response();
  if (request.method() == put) {
    response.setChunked(true);
    pump.pump(request, response).start();
    request.endHandler(() =&gt; response.end());
  } else {
    response.setStatusCode(400).end();
  };
}).listen(8080);</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_writing_http_2_frames">Writing HTTP/2 frames</h4>
<div class="paragraph">
<p>HTTP/2 is a framed protocol with various frames for the HTTP request/response model. The protocol allows other kind
of frames to be sent and received.</p>
</div>
<div class="paragraph">
<p>To send such frames, you can use the <code><a href="../../ceylondoc/vertx-core//http/HttpServerResponse.type.html#writeCustomFrame(int,%20int,%20io.vertx.core.buffer.Buffer)">writeCustomFrame</a></code> on the response.
Here&#8217;s an example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">import io.vertx.ceylon.core.buffer { buffer }

...


value frameType = 40;
value frameStatus = 10;
value payload = buffer.buffer("some data");

// Sending a frame to the client
response.writeCustomFrame(frameType, frameStatus, payload);</code></pre>
</div>
</div>
<div class="paragraph">
<p>These frames are sent immediately and are not subject to flow control - when such frame is sent there it may be done
before other <code>DATA</code> frames.</p>
</div>
</div>
<div class="sect3">
<h4 id="_stream_reset">Stream reset</h4>
<div class="paragraph">
<p>HTTP/1.x does not allow a clean reset of a request or a response stream, for example when a client uploads
a resource already present on the server, the server needs to accept the entire response.</p>
</div>
<div class="paragraph">
<p>HTTP/2 supports stream reset at any time during the request/response:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">// Reset the stream
request.response().reset();</code></pre>
</div>
</div>
<div class="paragraph">
<p>By default the <code>NO_ERROR</code> (0) error code is sent, another code can sent instead:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">// Cancel the stream
request.response().reset(8);</code></pre>
</div>
</div>
<div class="paragraph">
<p>The HTTP/2 specification defines the list of <a href="http://httpwg.org/specs/rfc7540.html#ErrorCodes">error codes</a> one can use.</p>
</div>
<div class="paragraph">
<p>The request handler are notified of stream reset events with the <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#exceptionHandler(io.vertx.core.Handler)">request handler</a></code> and
<code><a href="../../ceylondoc/vertx-core//http/HttpServerResponse.type.html#exceptionHandler(io.vertx.core.Handler)">response handler</a></code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">Code not translatable : class io.vertx.codetrans.lang.ceylon.CeylonWriter has not implemented renderInstanceOf</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_server_push">Server push</h4>
<div class="paragraph">
<p>Server push is a new feature of HTTP/2 that enables sending multiple responses in parallel for a single client request.</p>
</div>
<div class="paragraph">
<p>When a server process a request, it can push a request/response to the client:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">import io.vertx.ceylon.core.http { get }

...


value response = request.response();

// Push main.js to the client
response.push(get, "/main.js", (HttpServerResponse|Throwable ar) {

  if (is HttpServerResponse ar) {

    // The server is ready to push the response
    value pushedResponse = ar;

    // Send main.js response
    pushedResponse.putHeader("content-type", "application/json").end("alert(\"Push response hello\")");
  } else {
    print("Could not push client resource ``ar``");
  };
});

// Send the requested resource
response.sendFile("&lt;html&gt;&lt;head&gt;&lt;script src=\"/main.js\"&gt;&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;/body&gt;&lt;/html&gt;");</code></pre>
</div>
</div>
<div class="paragraph">
<p>When the server is ready to push the response, the push response handler is called and the handler can send the response.</p>
</div>
<div class="paragraph">
<p>The push response handler may receive a failure, for instance the client may cancel the push because it already has <code>main.js</code> in its
cache and does not want it anymore.</p>
</div>
<div class="paragraph">
<p>The <code><a href="../../ceylondoc/vertx-core//http/HttpServerResponse.type.html#push(io.vertx.core.http.HttpMethod,%20java.lang.String,%20java.lang.String,%20io.vertx.core.Handler)">push</a></code> method must be called before the initiating response ends, however
the pushed response can be written after.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_http_compression">HTTP Compression</h3>
<div class="paragraph">
<p>Vert.x comes with support for HTTP Compression out of the box.</p>
</div>
<div class="paragraph">
<p>This means you are able to automatically compress the body of the responses before they are sent back to the client.</p>
</div>
<div class="paragraph">
<p>If the client does not support HTTP compression the responses are sent back without compressing the body.</p>
</div>
<div class="paragraph">
<p>This allows to handle Client that support HTTP Compression and those that not support it at the same time.</p>
</div>
<div class="paragraph">
<p>To enable compression use can configure it with <code><a href="../../ceylondoc/vertx-core//http/HttpServerOptions.type.html#setCompressionSupported(boolean)">compressionSupported</a></code>.</p>
</div>
<div class="paragraph">
<p>By default compression is not enabled.</p>
</div>
<div class="paragraph">
<p>When HTTP compression is enabled the server will check if the client includes an <code>Accept-Encoding</code> header which
includes the supported compressions. Commonly used are deflate and gzip. Both are supported by Vert.x.</p>
</div>
<div class="paragraph">
<p>If such a header is found the server will automatically compress the body of the response with one of the supported
compressions and send it back to the client.</p>
</div>
<div class="paragraph">
<p>Be aware that compression may be able to reduce network traffic but is more CPU-intensive.</p>
</div>
</div>
<div class="sect2">
<h3 id="_creating_an_http_client">Creating an HTTP client</h3>
<div class="paragraph">
<p>You create an <code><a href="../../ceylondoc/vertx-core//http/HttpClient.type.html">HttpClient</a></code> instance with default options as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value client = vertx.createHttpClient();</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you want to configure options for the client, you create it as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value options = HttpClientOptions {
  keepAlive = false;
};
value client = vertx.createHttpClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Vert.x supports HTTP/2 over TLS <code>h2</code> and over TCP <code>h2c</code>.</p>
</div>
<div class="paragraph">
<p>By default the http client performs HTTP/1.1 requests, to perform HTTP/2 requests the <code><a href="../../ceylondoc/vertx-core//http/HttpClientOptions.type.html#setProtocolVersion(io.vertx.core.http.HttpVersion)">protocolVersion</a></code>
must be set to <code><a href="todo">HTTP_2</a></code>.</p>
</div>
<div class="paragraph">
<p>For <code>h2</code> requests, TLS must be enabled with <em>Application-Layer Protocol Negotiation</em>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">import io.vertx.ceylon.core.http { http_2 }

...


value options = HttpClientOptions {
  protocolVersion = "HTTP_2";
  ssl = true;
  useAlpn = true;
  trustAll = true;
};

value client = vertx.createHttpClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>For <code>h2c</code> requests, TLS must be disabled, the client will do an HTTP/1.1 requests and try an upgrade to HTTP/2:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">import io.vertx.ceylon.core.http { http_2 }

...


value options = HttpClientOptions {
  protocolVersion = "HTTP_2";
};

value client = vertx.createHttpClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p><code>h2c</code> connections can also be established directly, i.e connection started with a prior knowledge, when
<code><a href="../../ceylondoc/vertx-core//http/HttpClientOptions.type.html#setHttp2ClearTextUpgrade(boolean)">http2ClearTextUpgrade</a></code> options is set to false: after the
connection is established, the client will send the HTTP/2 connection preface and expect to receive
the same preface from the server.</p>
</div>
<div class="paragraph">
<p>The http server may not support HTTP/2, the actual version can be checked
with <code><a href="../../ceylondoc/vertx-core//http/HttpClientResponse.type.html#version()">version</a></code> when the response arrives.</p>
</div>
<div class="paragraph">
<p>When a clients connects to an HTTP/2 server, it sends to the server its <code><a href="../../ceylondoc/vertx-core//http/HttpClientOptions.type.html#getInitialSettings()">initial settings</a></code>.
The settings define how the server can use the connection, the default initial settings for a client are the default
values defined by the HTTP/2 RFC.</p>
</div>
</div>
<div class="sect2">
<h3 id="_logging_network_client_activity">Logging network client activity</h3>
<div class="paragraph">
<p>For debugging purposes, network activity can be logged.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value options = HttpClientOptions {
  logActivity = true;
};
value client = vertx.createHttpClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>See the chapter on <a href="#logging_network_activity">logging network activity</a> for a detailed explanation.</p>
</div>
</div>
<div class="sect2">
<h3 id="_making_requests">Making requests</h3>
<div class="paragraph">
<p>The http client is very flexible and there are various ways you can make requests with it.</p>
</div>
<div class="paragraph">
<p>Often you want to make many requests to the same host/port with an http client. To avoid you repeating the host/port
every time you make a request you can configure the client with a default host/port:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">// Set the default host
value options = HttpClientOptions {
  defaultHost = "wibble.com";
};
// Can also set default port if you want...
value client = vertx.createHttpClient(options);
client.getNow("/some-uri", (HttpClientResponse response) {
  print("Received response with status code ``response.statusCode()``");
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>Alternatively if you find yourself making lots of requests to different host/ports with the same client you can
simply specify the host/port when doing the request.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value client = vertx.createHttpClient();

// Specify both port and host name
client.getNow(8080, "myserver.mycompany.com", "/some-uri", (HttpClientResponse response) {
  print("Received response with status code ``response.statusCode()``");
});

// This time use the default port 80 but specify the host name
client.getNow("foo.othercompany.com", "/other-uri", (HttpClientResponse response) {
  print("Received response with status code ``response.statusCode()``");
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>Both methods of specifying host/port are supported for all the different ways of making requests with the client.</p>
</div>
<div class="sect3">
<h4 id="_simple_requests_with_no_request_body">Simple requests with no request body</h4>
<div class="paragraph">
<p>Often, you&#8217;ll want to make HTTP requests with no request body. This is usually the case with HTTP GET, OPTIONS and
HEAD requests.</p>
</div>
<div class="paragraph">
<p>The simplest way to do this with the Vert.x http client is using the methods prefixed with <code>Now</code>. For example
<code><a href="../../ceylondoc/vertx-core//http/HttpClient.type.html#getNow(int,%20java.lang.String,%20java.lang.String,%20io.vertx.core.Handler)">getNow</a></code>.</p>
</div>
<div class="paragraph">
<p>These methods create the http request and send it in a single method call and allow you to provide a handler that will be
called with the http response when it comes back.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value client = vertx.createHttpClient();

// Send a GET request
client.getNow("/some-uri", (HttpClientResponse response) {
  print("Received response with status code ``response.statusCode()``");
});

// Send a GET request
client.headNow("/other-uri", (HttpClientResponse response) {
  print("Received response with status code ``response.statusCode()``");
});</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_writing_general_requests">Writing general requests</h4>
<div class="paragraph">
<p>At other times you don&#8217;t know the request method you want to send until run-time. For that use case we provide
general purpose request methods such as <code><a href="../../ceylondoc/vertx-core//http/HttpClient.type.html#request(io.vertx.core.http.HttpMethod,%20int,%20java.lang.String,%20java.lang.String)">request</a></code> which allow you to specify
the HTTP method at run-time:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">import io.vertx.ceylon.core.http { get, post }

...

value client = vertx.createHttpClient();

client.request(get, "some-uri", (HttpClientResponse response) {
  print("Received response with status code ``response.statusCode()``");
}).end();

client.request(post, "foo-uri", (HttpClientResponse response) {
  print("Received response with status code ``response.statusCode()``");
}).end("some-data");</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_writing_request_bodies">Writing request bodies</h4>
<div class="paragraph">
<p>Sometimes you&#8217;ll want to write requests which have a body, or perhaps you want to write headers to a request
before sending it.</p>
</div>
<div class="paragraph">
<p>To do this you can call one of the specific request methods such as <code><a href="../../ceylondoc/vertx-core//http/HttpClient.type.html#post(int,%20java.lang.String,%20java.lang.String)">post</a></code> or
one of the general purpose request methods such as <code><a href="../../ceylondoc/vertx-core//http/HttpClient.type.html#request(io.vertx.core.http.HttpMethod,%20int,%20java.lang.String,%20java.lang.String)">request</a></code>.</p>
</div>
<div class="paragraph">
<p>These methods don&#8217;t send the request immediately, but instead return an instance of <code><a href="../../ceylondoc/vertx-core//http/HttpClientRequest.type.html">HttpClientRequest</a></code>
which can be used to write to the request body or write headers.</p>
</div>
<div class="paragraph">
<p>Here are some examples of writing a POST request with a body:
m</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value client = vertx.createHttpClient();

value request = client.post("some-uri", (HttpClientResponse response) {
  print("Received response with status code ``response.statusCode()``");
});

// Now do stuff with the request
request.putHeader("content-length", "1000");
request.putHeader("content-type", "text/plain");
request.write(body);

// Make sure the request is ended when you're done with it
request.end();

// Or fluently:

client.post("some-uri", (HttpClientResponse response) {
  print("Received response with status code ``response.statusCode()``");
}).putHeader("content-length", "1000").putHeader("content-type", "text/plain").write(body).end();

// Or event more simply:

client.post("some-uri", (HttpClientResponse response) {
  print("Received response with status code ``response.statusCode()``");
}).putHeader("content-type", "text/plain").end(body);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Methods exist to write strings in UTF-8 encoding and in any specific encoding and to write buffers:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">import io.vertx.ceylon.core.buffer { buffer_ = buffer }

...


// Write string encoded in UTF-8
request.write("some data");

// Write string encoded in specific encoding
request.write("some other data", "UTF-16");

// Write a buffer
value buffer = buffer_.buffer();
buffer.appendInt(123).appendLong(245);
request.write(buffer);</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you are just writing a single string or buffer to the HTTP request you can write it and end the request in a
single call to the <code>end</code> function.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">import io.vertx.ceylon.core.buffer { buffer_ = buffer }

...


// Write string and end the request (send it) in a single call
request.end("some simple data");

// Write buffer and end the request (send it) in a single call
value buffer = buffer_.buffer().appendDouble(12.34).appendLong(432);
request.end(buffer);</code></pre>
</div>
</div>
<div class="paragraph">
<p>When you&#8217;re writing to a request, the first call to <code>write</code> will result in the request headers being written
out to the wire.</p>
</div>
<div class="paragraph">
<p>The actual write is asynchronous and might not occur until some time after the call has returned.</p>
</div>
<div class="paragraph">
<p>Non-chunked HTTP requests with a request body require a <code>Content-Length</code> header to be provided.</p>
</div>
<div class="paragraph">
<p>Consequently, if you are not using chunked HTTP then you must set the <code>Content-Length</code> header before writing
to the request, as it will be too late otherwise.</p>
</div>
<div class="paragraph">
<p>If you are calling one of the <code>end</code> methods that take a string or buffer then Vert.x will automatically calculate
and set the <code>Content-Length</code> header before writing the request body.</p>
</div>
<div class="paragraph">
<p>If you are using HTTP chunking a a <code>Content-Length</code> header is not required, so you do not have to calculate the size
up-front.</p>
</div>
</div>
<div class="sect3">
<h4 id="_writing_request_headers">Writing request headers</h4>
<div class="paragraph">
<p>You can write headers to a request using the <code><a href="../../ceylondoc/vertx-core//http/HttpClientRequest.type.html#headers()">headers</a></code> multi-map as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">// Write some headers using the headers() multimap

value headers = request.headers();
headers.set("content-type", "application/json").set("other-header", "foo");</code></pre>
</div>
</div>
<div class="paragraph">
<p>The headers are an instance of <code><a href="../../ceylondoc/vertx-core//MultiMap.type.html">MultiMap</a></code> which provides operations for adding, setting and removing
entries. Http headers allow more than one value for a specific key.</p>
</div>
<div class="paragraph">
<p>You can also write headers using <code><a href="../../ceylondoc/vertx-core//http/HttpClientRequest.type.html#putHeader(java.lang.String,%20java.lang.String)">putHeader</a></code></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">// Write some headers using the putHeader method

request.putHeader("content-type", "application/json").putHeader("other-header", "foo");</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you wish to write headers to the request you must do so before any part of the request body is written.</p>
</div>
</div>
<div class="sect3">
<h4 id="_non_standard_http_methods_2">Non standard HTTP methods</h4>
<div class="paragraph">
<p>The <code><a href="todo">OTHER</a></code> HTTP method is used for non standard methods, when this method
is used, <code><a href="../../ceylondoc/vertx-core//http/HttpClientRequest.type.html#setRawMethod(java.lang.String)">setRawMethod</a></code> must be used to
set the raw method to send to the server.</p>
</div>
</div>
<div class="sect3">
<h4 id="_ending_http_requests">Ending HTTP requests</h4>
<div class="paragraph">
<p>Once you have finished with the HTTP request you must end it with one of the <code><a href="../../ceylondoc/vertx-core//http/HttpClientRequest.type.html#end(java.lang.String)">end</a></code>
operations.</p>
</div>
<div class="paragraph">
<p>Ending a request causes any headers to be written, if they have not already been written and the request to be marked
as complete.</p>
</div>
<div class="paragraph">
<p>Requests can be ended in several ways. With no arguments the request is simply ended:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">request.end();</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or a string or buffer can be provided in the call to <code>end</code>. This is like calling <code>write</code> with the string or buffer
before calling <code>end</code> with no arguments</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">import io.vertx.ceylon.core.buffer { buffer_ = buffer }

...

// End the request with a string
request.end("some-data");

// End it with a buffer
value buffer = buffer_.buffer().appendFloat(12.3).appendInt(321);
request.end(buffer);</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_chunked_http_requests">Chunked HTTP requests</h4>
<div class="paragraph">
<p>Vert.x supports <a href="http://en.wikipedia.org/wiki/Chunked_transfer_encoding">HTTP Chunked Transfer Encoding</a> for requests.</p>
</div>
<div class="paragraph">
<p>This allows the HTTP request body to be written in chunks, and is normally used when a large request body is being streamed
to the server, whose size is not known in advance.</p>
</div>
<div class="paragraph">
<p>You put the HTTP request into chunked mode using <code><a href="../../ceylondoc/vertx-core//http/HttpClientRequest.type.html#setChunked(boolean)">setChunked</a></code>.</p>
</div>
<div class="paragraph">
<p>In chunked mode each call to write will cause a new chunk to be written to the wire. In chunked mode there is
no need to set the <code>Content-Length</code> of the request up-front.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">request.setChunked(true);

// Write some chunks
variable value i = 0;
while (i &lt; 10) {
  request.write("this-is-chunk-``i``");
  i++};

request.end();</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_request_timeouts">Request timeouts</h4>
<div class="paragraph">
<p>You can set a timeout for a specific http request using <code><a href="../../ceylondoc/vertx-core//http/HttpClientRequest.type.html#setTimeout(long)">setTimeout</a></code>.</p>
</div>
<div class="paragraph">
<p>If the request does not return any data within the timeout period an exception will be passed to the exception handler
(if provided) and the request will be closed.</p>
</div>
</div>
<div class="sect3">
<h4 id="_handling_exceptions">Handling exceptions</h4>
<div class="paragraph">
<p>You can handle exceptions corresponding to a request by setting an exception handler on the
<code><a href="../../ceylondoc/vertx-core//http/HttpClientRequest.type.html">HttpClientRequest</a></code> instance:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value request = client.post("some-uri", (HttpClientResponse response) {
  print("Received response with status code ``response.statusCode()``");
});
request.exceptionHandler((Throwable e) {
  print("Received exception: ``e.getMessage()``");
  e.printStackTrace();
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>This does not handle non <em>2xx</em> response that need to be handled in the
<code><a href="../../ceylondoc/vertx-core//http/HttpClientResponse.type.html">HttpClientResponse</a></code> code:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value request = client.post("some-uri", (HttpClientResponse response) {
  if (response.statusCode() == 200) {
    print("Everything fine");
    return;
  };
  if (response.statusCode() == 500) {
    print("Unexpected behavior on the server side");
    return;
  };
});
request.end();</code></pre>
</div>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<div class="title">Important</div>
</td>
<td class="content">
<code>XXXNow</code> methods cannot receive an exception handler.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_specifying_a_handler_on_the_client_request">Specifying a handler on the client request</h4>
<div class="paragraph">
<p>Instead of providing a response handler in the call to create the client request object, alternatively, you can
not provide a handler when the request is created and set it later on the request object itself, using
<code><a href="../../ceylondoc/vertx-core//http/HttpClientRequest.type.html#handler(io.vertx.core.Handler)">handler</a></code>, for example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value request = client.post("some-uri");
request.handler((HttpClientResponse response) {
  print("Received response with status code ``response.statusCode()``");
});</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_using_the_request_as_a_stream">Using the request as a stream</h4>
<div class="paragraph">
<p>The <code><a href="../../ceylondoc/vertx-core//http/HttpClientRequest.type.html">HttpClientRequest</a></code> instance is also a <code><a href="../../ceylondoc/vertx-core//streams/WriteStream.type.html">WriteStream</a></code> which means
you can pump to it from any <code><a href="../../ceylondoc/vertx-core//streams/ReadStream.type.html">ReadStream</a></code> instance.</p>
</div>
<div class="paragraph">
<p>For, example, you could pump a file on disk to a http request body as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">import io.vertx.ceylon.core.streams { pump_ = pump }

...


request.setChunked(true);
value pump = pump_.pump(file, request);
file.endHandler(() =&gt; request.end());
pump.start();</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_writing_http_2_frames_2">Writing HTTP/2 frames</h4>
<div class="paragraph">
<p>HTTP/2 is a framed protocol with various frames for the HTTP request/response model. The protocol allows other kind
of frames to be sent and received.</p>
</div>
<div class="paragraph">
<p>To send such frames, you can use the <code><a href="../../ceylondoc/vertx-core//http/HttpClientRequest.type.html#write(io.vertx.core.buffer.Buffer)">write</a></code> on the request. Here&#8217;s an example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">import io.vertx.ceylon.core.buffer { buffer }

...


value frameType = 40;
value frameStatus = 10;
value payload = buffer.buffer("some data");

// Sending a frame to the server
request.writeCustomFrame(frameType, frameStatus, payload);</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_stream_reset_2">Stream reset</h4>
<div class="paragraph">
<p>HTTP/1.x does not allow a clean reset of a request or a response stream, for example when a client uploads a resource already
present on the server, the server needs to accept the entire response.</p>
</div>
<div class="paragraph">
<p>HTTP/2 supports stream reset at any time during the request/response:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">request.reset();</code></pre>
</div>
</div>
<div class="paragraph">
<p>By default the NO_ERROR (0) error code is sent, another code can sent instead:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">request.reset(8);</code></pre>
</div>
</div>
<div class="paragraph">
<p>The HTTP/2 specification defines the list of <a href="http://httpwg.org/specs/rfc7540.html#ErrorCodes">error codes</a> one can use.</p>
</div>
<div class="paragraph">
<p>The request handler are notified of stream reset events with the <code><a href="../../ceylondoc/vertx-core//http/HttpClientRequest.type.html#exceptionHandler(io.vertx.core.Handler)">request handler</a></code> and
<code><a href="../../ceylondoc/vertx-core//http/HttpClientResponse.type.html#exceptionHandler(io.vertx.core.Handler)">response handler</a></code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">Code not translatable : class io.vertx.codetrans.lang.ceylon.CeylonWriter has not implemented renderInstanceOf</code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_handling_http_responses">Handling http responses</h3>
<div class="paragraph">
<p>You receive an instance of <code><a href="../../ceylondoc/vertx-core//http/HttpClientResponse.type.html">HttpClientResponse</a></code> into the handler that you specify in of
the request methods or by setting a handler directly on the <code><a href="../../ceylondoc/vertx-core//http/HttpClientRequest.type.html">HttpClientRequest</a></code> object.</p>
</div>
<div class="paragraph">
<p>You can query the status code and the status message of the response with <code><a href="../../ceylondoc/vertx-core//http/HttpClientResponse.type.html#statusCode()">statusCode</a></code>
and <code><a href="../../ceylondoc/vertx-core//http/HttpClientResponse.type.html#statusMessage()">statusMessage</a></code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">client.getNow("some-uri", (HttpClientResponse response) {
  // the status code - e.g. 200 or 404
  print("Status code is ``response.statusCode()``");

  // the status message e.g. "OK" or "Not Found".
  print("Status message is ``response.statusMessage()``");
});</code></pre>
</div>
</div>
<div class="sect3">
<h4 id="_using_the_response_as_a_stream">Using the response as a stream</h4>
<div class="paragraph">
<p>The <code><a href="../../ceylondoc/vertx-core//http/HttpClientResponse.type.html">HttpClientResponse</a></code> instance is also a <code><a href="../../ceylondoc/vertx-core//streams/ReadStream.type.html">ReadStream</a></code> which means
you can pump it to any <code><a href="../../ceylondoc/vertx-core//streams/WriteStream.type.html">WriteStream</a></code> instance.</p>
</div>
</div>
<div class="sect3">
<h4 id="_response_headers_and_trailers">Response headers and trailers</h4>
<div class="paragraph">
<p>Http responses can contain headers. Use <code><a href="../../ceylondoc/vertx-core//http/HttpClientResponse.type.html#headers()">headers</a></code> to get the headers.</p>
</div>
<div class="paragraph">
<p>The object returned is a <code><a href="../../ceylondoc/vertx-core//MultiMap.type.html">MultiMap</a></code> as HTTP headers can contain multiple values for single keys.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value contentType = response.headers().get("content-type");
value contentLength = response.headers().get("content-lengh");</code></pre>
</div>
</div>
<div class="paragraph">
<p>Chunked HTTP responses can also contain trailers - these are sent in the last chunk of the response body.</p>
</div>
<div class="paragraph">
<p>You use <code><a href="../../ceylondoc/vertx-core//http/HttpClientResponse.type.html#trailers()">trailers</a></code> to get the trailers. Trailers are also a <code><a href="../../ceylondoc/vertx-core//MultiMap.type.html">MultiMap</a></code>.</p>
</div>
</div>
<div class="sect3">
<h4 id="_reading_the_request_body">Reading the request body</h4>
<div class="paragraph">
<p>The response handler is called when the headers of the response have been read from the wire.</p>
</div>
<div class="paragraph">
<p>If the response has a body this might arrive in several pieces some time after the headers have been read. We
don&#8217;t wait for all the body to arrive before calling the response handler as the response could be very large and we
might be waiting a long time, or run out of memory for large responses.</p>
</div>
<div class="paragraph">
<p>As parts of the response body arrive, the <code><a href="../../ceylondoc/vertx-core//http/HttpClientResponse.type.html#handler(io.vertx.core.Handler)">handler</a></code> is called with
a <code><a href="../../ceylondoc/vertx-core//buffer/Buffer.type.html">Buffer</a></code> representing the piece of the body:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">client.getNow("some-uri", (HttpClientResponse response) {

  response.handler((Buffer buffer) {
    print("Received a part of the response body: ``buffer``");
  });
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you know the response body is not very large and want to aggregate it all in memory before handling it, you can
either aggregate it yourself:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">import io.vertx.ceylon.core.buffer { buffer }

...


client.getNow("some-uri", (HttpClientResponse response) {

  // Create an empty buffer
  value totalBuffer = buffer.buffer();

  response.handler((Buffer buffer) {
    print("Received a part of the response body: ``buffer.length()``");

    totalBuffer.appendBuffer(buffer);
  });

  response.endHandler(() {
    // Now all the body has been read
    print("Total response body length is ``totalBuffer.length()``");
  });
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or you can use the convenience <code><a href="../../ceylondoc/vertx-core//http/HttpClientResponse.type.html#bodyHandler(io.vertx.core.Handler)">bodyHandler</a></code> which
is called with the entire body when the response has been fully read:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">client.getNow("some-uri", (HttpClientResponse response) {

  response.bodyHandler((Buffer totalBuffer) {
    // Now all the body has been read
    print("Total response body length is ``totalBuffer.length()``");
  });
});</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_response_end_handler">Response end handler</h4>
<div class="paragraph">
<p>The response <code><a href="../../ceylondoc/vertx-core//http/HttpClientResponse.type.html#endHandler(io.vertx.core.Handler)">endHandler</a></code> is called when the entire response body has been read
or immediately after the headers have been read and the response handler has been called if there is no body.</p>
</div>
</div>
<div class="sect3">
<h4 id="_reading_cookies_from_the_response">Reading cookies from the response</h4>
<div class="paragraph">
<p>You can retrieve the list of cookies from a response using <code><a href="../../ceylondoc/vertx-core//http/HttpClientResponse.type.html#cookies()">cookies</a></code>.</p>
</div>
<div class="paragraph">
<p>Alternatively you can just parse the <code>Set-Cookie</code> headers yourself in the response.</p>
</div>
</div>
<div class="sect3">
<h4 id="_100_continue_handling">100-Continue handling</h4>
<div class="paragraph">
<p>According to the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html">HTTP 1.1 specification</a> a client can set a
header <code>Expect: 100-Continue</code> and send the request header before sending the rest of the request body.</p>
</div>
<div class="paragraph">
<p>The server can then respond with an interim response status <code>Status: 100 (Continue)</code> to signify to the client that
it is ok to send the rest of the body.</p>
</div>
<div class="paragraph">
<p>The idea here is it allows the server to authorise and accept/reject the request before large amounts of data are sent.
Sending large amounts of data if the request might not be accepted is a waste of bandwidth and ties up the server
in reading data that it will just discard.</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1">Vert.x allows you to set a `link:../../ceylondoc/vertx-core//http/HttpClientRequest.type.html#continueHandler((@io.vertx.codegen.annotations.Nullable </dt>
<dd>
<p>io.vertx.core.Handler))[continueHandler]` on the
client request object</p>
</dd>
</dl>
</div>
<div class="paragraph">
<p>This will be called if the server sends back a <code>Status: 100 (Continue)</code> response to signify that it is ok to send
the rest of the request.</p>
</div>
<div class="paragraph">
<p>This is used in conjunction with `<a href="../../ceylondoc/vertx-core//http/HttpClientRequest.type.html#sendHead()">sendHead</a>`to send the head of the request.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s an example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value request = client.put("some-uri", (HttpClientResponse response) {
  print("Received response with status code ``response.statusCode()``");
});

request.putHeader("Expect", "100-Continue");

request.continueHandler(() {
  // OK to send rest of body
  request.write("Some data");
  request.write("Some more data");
  request.end();
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>On the server side a Vert.x http server can be configured to automatically send back 100 Continue interim responses
when it receives an <code>Expect: 100-Continue</code> header.</p>
</div>
<div class="paragraph">
<p>This is done by setting the option <code><a href="../../ceylondoc/vertx-core//http/HttpServerOptions.type.html#setHandle100ContinueAutomatically(boolean)">handle100ContinueAutomatically</a></code>.</p>
</div>
<div class="paragraph">
<p>If you&#8217;d prefer to decide whether to send back continue responses manually, then this property should be set to
<code>false</code> (the default), then you can inspect the headers and call <code><a href="../../ceylondoc/vertx-core//http/HttpServerResponse.type.html#writeContinue()">writeContinue</a></code>
to have the client continue sending the body:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">httpServer.requestHandler((HttpServerRequest request) {
  if (request.getHeader("Expect").equalsIgnoreCase("100-Continue")) {

    // Send a 100 continue response
    request.response().writeContinue();

    // The client should send the body when it receives the 100 response
    request.bodyHandler((Buffer body) {
      // Do something with body
    });

    request.endHandler(() {
      request.response().end();
    });
  };
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also reject the request by sending back a failure status code directly: in this case the body
should either be ignored or the connection should be closed (100-Continue is a performance hint and
cannot be a logical protocol constraint):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">httpServer.requestHandler((HttpServerRequest request) {
  if (request.getHeader("Expect").equalsIgnoreCase("100-Continue")) {

    //
    value rejectAndClose = true;
    if (rejectAndClose) {

      // Reject with a failure code and close the connection
      // this is probably best with persistent connection
      request.response().setStatusCode(405).putHeader("Connection", "close").end();
    } else {

      // Reject with a failure code and ignore the body
      // this may be appropriate if the body is small
      request.response().setStatusCode(405).end();
    };
  };
});</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_client_push">Client push</h4>
<div class="paragraph">
<p>Server push is a new feature of HTTP/2 that enables sending multiple responses in parallel for a single client request.</p>
</div>
<div class="paragraph">
<p>A push handler can be set on a request to receive the request/response pushed by the server:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value request = client.get("/index.html", (HttpClientResponse response) {
  // Process index.html response
});

// Set a push handler to be aware of any resource pushed by the server
request.pushHandler((HttpClientRequest pushedRequest) {

  // A resource is pushed for this request
  print("Server pushed ``pushedRequest.path()``");

  // Set an handler for the response
  pushedRequest.handler((HttpClientResponse pushedResponse) {
    print("The response for the pushed request");
  });
});

// End the request
request.end();</code></pre>
</div>
</div>
<div class="paragraph">
<p>If the client does not want to receive a pushed request, it can reset the stream:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">request.pushHandler((HttpClientRequest pushedRequest) {
  if (pushedRequest.path() == "/main.js") {
    pushedRequest.reset();
  } else {
    // Handle it
  };
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>When no handler is set, any stream pushed will be automatically cancelled by the client with
a stream reset (<code>8</code> error code).</p>
</div>
</div>
<div class="sect3">
<h4 id="_receiving_custom_http_2_frames_2">Receiving custom HTTP/2 frames</h4>
<div class="paragraph">
<p>HTTP/2 is a framed protocol with various frames for the HTTP request/response model. The protocol allows other kind of
frames to be sent and received.</p>
</div>
<div class="paragraph">
<p>To receive custom frames, you can use the customFrameHandler on the request, this will get called every time a custom
frame arrives. Here&#8217;s an example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">response.customFrameHandler((HttpFrame frame) {

  print("Received a frame type=``frame.type()`` payload``frame.payload().toString()``");
});</code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_enabling_compression_on_the_client">Enabling compression on the client</h3>
<div class="paragraph">
<p>The http client comes with support for HTTP Compression out of the box.</p>
</div>
<div class="paragraph">
<p>This means the client can let the remote http server know that it supports compression, and will be able to handle
compressed response bodies.</p>
</div>
<div class="paragraph">
<p>An http server is free to either compress with one of the supported compression algorithms or to send the body back
without compressing it at all. So this is only a hint for the Http server which it may ignore at will.</p>
</div>
<div class="paragraph">
<p>To tell the http server which compression is supported by the client it will include an <code>Accept-Encoding</code> header with
the supported compression algorithm as value. Multiple compression algorithms are supported. In case of Vert.x this
will result in the following header added:</p>
</div>
<div class="literalblock">
<div class="content">
<pre>Accept-Encoding: gzip, deflate</pre>
</div>
</div>
<div class="paragraph">
<p>The server will choose then from one of these. You can detect if a server ompressed the body by checking for the
<code>Content-Encoding</code> header in the response sent back from it.</p>
</div>
<div class="paragraph">
<p>If the body of the response was compressed via gzip it will include for example the following header:</p>
</div>
<div class="literalblock">
<div class="content">
<pre>Content-Encoding: gzip</pre>
</div>
</div>
<div class="paragraph">
<p>To enable compression set <code><a href="../../ceylondoc/vertx-core//http/HttpClientOptions.type.html#setTryUseCompression(boolean)">tryUseCompression</a></code> on the options
used when creating the client.</p>
</div>
<div class="paragraph">
<p>By default compression is disabled.</p>
</div>
</div>
<div class="sect2">
<h3 id="_http_1_x_pooling_and_keep_alive">HTTP/1.x pooling and keep alive</h3>
<div class="paragraph">
<p>Http keep alive allows http connections to be used for more than one request. This can be a more efficient use of
connections when you&#8217;re making multiple requests to the same server.</p>
</div>
<div class="paragraph">
<p>For HTTP/1.x versions, the http client supports pooling of connections, allowing you to reuse connections between requests.</p>
</div>
<div class="paragraph">
<p>For pooling to work, keep alive must be true using <code><a href="../../ceylondoc/vertx-core//http/HttpClientOptions.type.html#setKeepAlive(boolean)">keepAlive</a></code>
on the options used when configuring the client. The default value is true.</p>
</div>
<div class="paragraph">
<p>When keep alive is enabled. Vert.x will add a <code>Connection: Keep-Alive</code> header to each HTTP/1.0 request sent.
When keep alive is disabled. Vert.x will add a <code>Connection: Close</code> header to each HTTP/1.1 request sent to signal
that the connection will be closed after completion of the response.</p>
</div>
<div class="paragraph">
<p>The maximum number of connections to pool <strong>for each server</strong> is configured using <code><a href="../../ceylondoc/vertx-core//http/HttpClientOptions.type.html#setMaxPoolSize(int)">maxPoolSize</a></code></p>
</div>
<div class="paragraph">
<p>When making a request with pooling enabled, Vert.x will create a new connection if there are less than the maximum number of
connections already created for that server, otherwise it will add the request to a queue.</p>
</div>
<div class="paragraph">
<p>Keep alive connections will not be closed by the client automatically. To close them you can close the client instance.</p>
</div>
<div class="paragraph">
<p>Alternatively you can set idle timeout using <code><a href="../../ceylondoc/vertx-core//http/HttpClientOptions.type.html#setIdleTimeout(int)">idleTimeout</a></code> - any
connections not used within this timeout will be closed. Please note the idle timeout value is in seconds not milliseconds.</p>
</div>
</div>
<div class="sect2">
<h3 id="_http_1_1_pipe_lining">HTTP/1.1 pipe-lining</h3>
<div class="paragraph">
<p>The client also supports pipe-lining of requests on a connection.</p>
</div>
<div class="paragraph">
<p>Pipe-lining means another request is sent on the same connection before the response from the preceding one has
returned. Pipe-lining is not appropriate for all requests.</p>
</div>
<div class="paragraph">
<p>To enable pipe-lining, it must be enabled using <code><a href="../../ceylondoc/vertx-core//http/HttpClientOptions.type.html#setPipelining(boolean)">pipelining</a></code>.
By default pipe-lining is disabled.</p>
</div>
<div class="paragraph">
<p>When pipe-lining is enabled requests will be written to connections without waiting for previous responses to return.</p>
</div>
<div class="paragraph">
<p>The number of pipe-lined requests over a single connection is limited by <code><a href="../../ceylondoc/vertx-core//http/HttpClientOptions.type.html#setPipeliningLimit(int)">pipeliningLimit</a></code>.
This option defines the maximum number of http requests sent to the server awaiting for a response. This limit ensures the
fairness of the distribution of the client requests over the connections to the same server.</p>
</div>
</div>
<div class="sect2">
<h3 id="_http_2_multiplexing">HTTP/2 multiplexing</h3>
<div class="paragraph">
<p>HTTP/2 advocates to use a single connection to a server, by default the http client uses a single
connection for each server, all the streams to the same server are multiplexed over the same connection.</p>
</div>
<div class="paragraph">
<p>When the clients needs to use more than a single connection and use pooling, the <code><a href="../../ceylondoc/vertx-core//http/HttpClientOptions.type.html#setHttp2MaxPoolSize(int)">http2MaxPoolSize</a></code>
shall be used.</p>
</div>
<div class="paragraph">
<p>When it is desirable to limit the number of multiplexed streams per connection and use a connection
pool instead of a single connection, <code><a href="../../ceylondoc/vertx-core//http/HttpClientOptions.type.html#setHttp2MultiplexingLimit(int)">http2MultiplexingLimit</a></code>
can be used.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value clientOptions = HttpClientOptions {
  http2MultiplexingLimit = 10;
  http2MaxPoolSize = 3;
};

// Uses up to 3 connections and up to 10 streams per connection
value client = vertx.createHttpClient(clientOptions);</code></pre>
</div>
</div>
<div class="paragraph">
<p>The multiplexing limit for a connection is a setting set on the client that limits the number of streams
of a single connection. The effective value can be even lower if the server sets a lower limit
with the <code><a href="../../ceylondoc/vertx-core//http/Http2Settings.type.html#setMaxConcurrentStreams(long)">SETTINGS_MAX_CONCURRENT_STREAMS</a></code> setting.</p>
</div>
<div class="paragraph">
<p>HTTP/2 connections will not be closed by the client automatically. To close them you can call <code><a href="../../ceylondoc/vertx-core//http/HttpConnection.type.html#close()">close</a></code>
or close the client instance.</p>
</div>
<div class="paragraph">
<p>Alternatively you can set idle timeout using <code><a href="../../ceylondoc/vertx-core//http/HttpClientOptions.type.html#setIdleTimeout(int)">idleTimeout</a></code> - any
connections not used within this timeout will be closed. Please note the idle timeout value is in seconds not milliseconds.</p>
</div>
</div>
<div class="sect2">
<h3 id="_http_connections">HTTP connections</h3>
<div class="paragraph">
<p>The <code><a href="../../ceylondoc/vertx-core//http/HttpConnection.type.html">HttpConnection</a></code> offers the API for dealing with HTTP connection events, lifecycle
and settings.</p>
</div>
<div class="paragraph">
<p>HTTP/2 implements fully the <code><a href="../../ceylondoc/vertx-core//http/HttpConnection.type.html">HttpConnection</a></code> API.</p>
</div>
<div class="paragraph">
<p>HTTP/1.x implements partially the <code><a href="../../ceylondoc/vertx-core//http/HttpConnection.type.html">HttpConnection</a></code> API: only the close operation,
the close handler and exception handler are implemented. This protocol does not provide semantics for
the other operations.</p>
</div>
<div class="sect3">
<h4 id="_server_connections">Server connections</h4>
<div class="paragraph">
<p>The <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#connection()">connection</a></code> method returns the request connection on the server:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value connection = request.connection();</code></pre>
</div>
</div>
<div class="paragraph">
<p>A connection handler can be set on the server to be notified of any incoming connection:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value server = vertx.createHttpServer(http2Options);

server.connectionHandler((HttpConnection connection) {
  print("A client connected");
});</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_client_connections">Client connections</h4>
<div class="paragraph">
<p>The <code><a href="../../ceylondoc/vertx-core//http/HttpClientRequest.type.html#connection()">connection</a></code> method returns the request connection on the client:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">value connection = request.connection();</code></pre>
</div>
</div>
<div class="paragraph">
<p>A connection handler can be set on the request to be notified when the connection happens:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">request.connectionHandler((HttpConnection connection) {
  print("Connected to the server");
});</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_connection_settings">Connection settings</h4>
<div class="paragraph">
<p>The configuration of an HTTP/2 is configured by the <code><a href="../../ceylondoc/vertx-core//http/Http2Settings.type.html">Http2Settings</a></code> data object.</p>
</div>
<div class="paragraph">
<p>Each endpoint must respect the settings sent by the other side of the connection.</p>
</div>
<div class="paragraph">
<p>When a connection is established, the client and the server exchange initial settings. Initial settings
are configured by <code><a href="../../ceylondoc/vertx-core//http/HttpClientOptions.type.html#setInitialSettings(io.vertx.core.http.Http2Settings)">initialSettings</a></code> on the client and
<code><a href="../../ceylondoc/vertx-core//http/HttpServerOptions.type.html#setInitialSettings(io.vertx.core.http.Http2Settings)">initialSettings</a></code> on the server.</p>
</div>
<div class="paragraph">
<p>The settings can be changed at any time after the connection is established:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">connection.updateSettings(Http2Settings {
  maxConcurrentStreams = 100;
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>As the remote side should acknowledge on reception of the settings update, it&#8217;s possible to give a callback
to be notified of the acknowledgment:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">connection.updateSettings(Http2Settings {
  maxConcurrentStreams = 100;
}, (Throwable? ar) {
  if (!exists ar) {
    print("The settings update has been acknowledged ");
  };
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>Conversely the <code><a href="../../ceylondoc/vertx-core//http/HttpConnection.type.html#remoteSettingsHandler(io.vertx.core.Handler)">remoteSettingsHandler</a></code> is notified
when the new remote settings are received:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">connection.remoteSettingsHandler((Http2Settings settings) {
  print("Received new settings");
});</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
this only applies to the HTTP/2 protocol
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_connection_ping">Connection ping</h4>
<div class="paragraph">
<p>HTTP/2 connection ping is useful for determining the connection round-trip time or check the connection
validity: <code><a href="../../ceylondoc/vertx-core//http/HttpConnection.type.html#ping(io.vertx.core.buffer.Buffer,%20io.vertx.core.Handler)">ping</a></code> sends a <code>PING</code> frame to the remote
endpoint:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">import io.vertx.ceylon.core.buffer { buffer }

...

value data = buffer.buffer();
variable value i = 0;
while (i &lt; 8) {
  data.appendByte(i);
  i++};
connection.ping(data, (Buffer|Throwable pong) {
  print("Remote side replied");
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>Vert.x will send automatically an acknowledgement when a <code>PING</code> frame is received,
an handler can be set to be notified for each ping received:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">connection.pingHandler((Buffer ping) {
  print("Got pinged by remote side");
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>The handler is just notified, the acknowledgement is sent whatsoever. Such feature is aimed for
implementing  protocols on top of HTTP/2.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
this only applies to the HTTP/2 protocol
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_connection_shutdown_and_go_away">Connection shutdown and go away</h4>
<div class="paragraph">
<p>Calling <code><a href="../../ceylondoc/vertx-core//http/HttpConnection.type.html#shutdown()">shutdown</a></code> will send a <code>GOAWAY</code> frame to the
remote side of the connection, asking it to stop creating streams: a client will stop doing new requests
and a server will stop pushing responses. After the <code>GOAWAY</code> frame is sent, the connection
waits some time (30 seconds by default) until all current streams closed and close the connection:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">connection.shutdown();</code></pre>
</div>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1">The `link:../../ceylondoc/vertx-core//http/HttpConnection.type.html#shutdownHandler((@io.vertx.codegen.annotations.Nullable </dt>
<dd>
<p>io.vertx.core.Handler))[shutdownHandler]` notifies when all streams have been closed, the
connection is not yet closed.</p>
</dd>
</dl>
</div>
<div class="paragraph">
<p>It&#8217;s possible to just send a <code>GOAWAY</code> frame, the main difference with a shutdown is that
it will just tell the remote side of the connection to stop creating new streams without scheduling a connection
close:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">connection.goAway(0);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Conversely, it is also possible to be notified when <code>GOAWAY</code> are received:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">connection.goAwayHandler((GoAway goAway) {
  print("Received a go away frame");
});</code></pre>
</div>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1">The `link:../../ceylondoc/vertx-core//http/HttpConnection.type.html#shutdownHandler((@io.vertx.codegen.annotations.Nullable </dt>
<dd>
<p>io.vertx.core.Handler))[shutdownHandler]` will be called when all current streams
have been closed and the connection can be closed:</p>
</dd>
</dl>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">connection.goAway(0);
connection.shutdownHandler(() {

  // All streams are closed, close the connection
  connection.close();
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>This applies also when a <code>GOAWAY</code> is received.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
this only applies to the HTTP/2 protocol
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_connection_close">Connection close</h4>
<div class="paragraph">
<p>Connection <code><a href="../../ceylondoc/vertx-core//http/HttpConnection.type.html#close()">close</a></code> closes the connection:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>it closes the socket for HTTP/1.x</p>
</li>
<li>
<p>a shutdown with no delay for HTTP/2, the <code>GOAWAY</code> frame will still be sent before the connection is closed. *</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The <code><a href="../../ceylondoc/vertx-core//http/HttpConnection.type.html#closeHandler(io.vertx.core.Handler)">closeHandler</a></code> notifies when a connection is closed.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_httpclient_usage">HttpClient usage</h3>
<div class="paragraph">
<p>The HttpClient can be used in a Verticle or embedded.</p>
</div>
<div class="paragraph">
<p>When used in a Verticle, the Verticle <strong>should use its own client instance</strong>.</p>
</div>
<div class="paragraph">
<p>More generally a client should not be shared between different Vert.x contexts as it can lead to unexpected behavior.</p>
</div>
<div class="paragraph">
<p>For example a keep-alive connection will call the client handlers on the context of the request that opened the connection, subsequent requests will use
the same context.</p>
</div>
<div class="paragraph">
<p>When this happen Vert.x detects it and log a warn:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>Reusing a connection with a different context: an HttpClient is probably shared between different Verticles</pre>
</div>
</div>
<div class="paragraph">
<p>The HttpClient can be embedded in a non Vert.x thread like a unit test or a plain java <code>main</code>: the client handlers
will be called by different Vert.x threads and contexts, such contexts are created as needed. For production this
usage is not recommended.</p>
</div>
</div>
<div class="sect2">
<h3 id="_server_sharing">Server sharing</h3>
<div class="paragraph">
<p>When several HTTP servers listen on the same port, vert.x orchestrates the request handling using a
round-robin strategy.</p>
</div>
<div class="paragraph">
<p>Let&#8217;s take a verticle creating a HTTP server such as:</p>
</div>
<div class="listingblock">
<div class="title">io.vertx.examples.http.sharing.HttpServerVerticle</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">vertx.createHttpServer().requestHandler((HttpServerRequest request) {
  request.response().end("Hello from server ``this``");
}).listen(8080);</code></pre>
</div>
</div>
<div class="paragraph">
<p>This service is listening on the port 8080. So, when this verticle is instantiated multiple times as with:
<code>vertx run io.vertx.examples.http.sharing.HttpServerVerticle -instances 2</code>, what&#8217;s happening ? If both
verticles would bind to the same port, you would receive a socket exception. Fortunately, vert.x is handling
this case for you. When you deploy another server on the same host and port as an existing server it doesn&#8217;t
actually try and create a new server listening on the same host/port. It binds only once to the socket. When
receiving a request it calls the server handlers following a round robin strategy.</p>
</div>
<div class="paragraph">
<p>Let&#8217;s now imagine a client such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">vertx.setPeriodic(100, (Integer l) {
  vertx.createHttpClient().getNow(8080, "localhost", "/", (HttpClientResponse resp) {
    resp.bodyHandler((Buffer body) {
      print(body.toString("ISO-8859-1"));
    });
  });
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>Vert.x delegates the requests to one of the server sequentially:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code>Hello from i.v.e.h.s.HttpServerVerticle@1
Hello from i.v.e.h.s.HttpServerVerticle@2
Hello from i.v.e.h.s.HttpServerVerticle@1
Hello from i.v.e.h.s.HttpServerVerticle@2
...</code></pre>
</div>
</div>
<div class="paragraph">
<p>Consequently the servers can scale over available cores while each Vert.x verticle instance remains strictly
single threaded, and you don&#8217;t have to do any special tricks like writing load-balancers in order to scale your
server on your multi-core machine.</p>
</div>
</div>
<div class="sect2">
<h3 id="_using_https_with_vert_x">Using HTTPS with Vert.x</h3>
<div class="paragraph">
<p>Vert.x http servers and clients can be configured to use HTTPS in exactly the same way as net servers.</p>
</div>
<div class="paragraph">
<p>Please see <a href="#ssl">configuring net servers to use SSL</a> for more information.</p>
</div>
</div>
<div class="sect2">
<h3 id="_websockets">WebSockets</h3>
<div class="paragraph">
<p><a href="http://en.wikipedia.org/wiki/WebSocket">WebSockets</a> are a web technology that allows a full duplex socket-like
connection between HTTP servers and HTTP clients (typically browsers).</p>
</div>
<div class="paragraph">
<p>Vert.x supports WebSockets on both the client and server-side.</p>
</div>
<div class="sect3">
<h4 id="_websockets_on_the_server">WebSockets on the server</h4>
<div class="paragraph">
<p>There are two ways of handling WebSockets on the server side.</p>
</div>
<div class="sect4">
<h5 id="_websocket_handler">WebSocket handler</h5>
<div class="paragraph">
<p>The first way involves providing a <code><a href="../../ceylondoc/vertx-core//http/HttpServer.type.html#websocketHandler(io.vertx.core.Handler)">websocketHandler</a></code>
on the server instance.</p>
</div>
<div class="paragraph">
<p>When a WebSocket connection is made to the server, the handler will be called, passing in an instance of
<code><a href="../../ceylondoc/vertx-core//http/ServerWebSocket.type.html">ServerWebSocket</a></code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">server.websocketHandler((ServerWebSocket websocket) {
  print("Connected!");
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can choose to reject the WebSocket by calling <code><a href="../../ceylondoc/vertx-core//http/ServerWebSocket.type.html#reject()">reject</a></code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">server.websocketHandler((ServerWebSocket websocket) {
  if (websocket.path() == "/myapi") {
    websocket.reject();
  } else {
    // Do something
  };
});</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_upgrading_to_websocket">Upgrading to WebSocket</h5>
<div class="paragraph">
<p>The second way of handling WebSockets is to handle the HTTP Upgrade request that was sent from the client, and
call <code><a href="../../ceylondoc/vertx-core//http/HttpServerRequest.type.html#upgrade()">upgrade</a></code> on the server request.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">server.requestHandler((HttpServerRequest request) {
  if (request.path() == "/myapi") {

    value websocket = request.upgrade();
    // Do something

  } else {
    // Reject
    request.response().setStatusCode(400).end();
  };
});</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_the_server_websocket">The server WebSocket</h5>
<div class="paragraph">
<p>The <code><a href="../../ceylondoc/vertx-core//http/ServerWebSocket.type.html">ServerWebSocket</a></code> instance enables you to retrieve the <code><a href="../../ceylondoc/vertx-core//http/ServerWebSocket.type.html#headers()">headers</a></code>,
<code><a href="../../ceylondoc/vertx-core//http/ServerWebSocket.type.html#path()">path</a></code>, <code><a href="../../ceylondoc/vertx-core//http/ServerWebSocket.type.html#query()">query</a></code> and
<code><a href="../../ceylondoc/vertx-core//http/ServerWebSocket.type.html#uri()">URI</a></code> of the HTTP request of the WebSocket handshake.</p>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_websockets_on_the_client">WebSockets on the client</h4>
<div class="paragraph">
<p>The Vert.x <code><a href="../../ceylondoc/vertx-core//http/HttpClient.type.html">HttpClient</a></code> supports WebSockets.</p>
</div>
<div class="paragraph">
<p>You can connect a WebSocket to a server using one of the <code><a href="../../ceylondoc/vertx-core//http/HttpClient.type.html#websocket(int,%20java.lang.String,%20java.lang.String,%20io.vertx.core.Handler)">websocket</a></code> operations and
providing a handler.</p>
</div>
<div class="paragraph">
<p>The handler will be called with an instance of <code><a href="../../ceylondoc/vertx-core//http/WebSocket.type.html">WebSocket</a></code> when the connection has been made:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">client.websocket("/some-uri", (WebSocket websocket) {
  print("Connected!");
});</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_writing_messages_to_websockets">Writing messages to WebSockets</h4>
<div class="paragraph">
<p>If you wish to write a single binary WebSocket message to the WebSocket you can do this with
<code><a href="../../ceylondoc/vertx-core//http/WebSocket.type.html#writeBinaryMessage(io.vertx.core.buffer.Buffer)">writeBinaryMessage</a></code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">import io.vertx.ceylon.core.buffer { buffer_ = buffer }

...

// Write a simple message
value buffer = buffer_.buffer().appendInt(123).appendFloat(1.23);

websocket.writeBinaryMessage(buffer);</code></pre>
</div>
</div>
<div class="paragraph">
<p>If the WebSocket message is larger than the maximum websocket frame size as configured with
<code><a href="../../ceylondoc/vertx-core//http/HttpClientOptions.type.html#setMaxWebsocketFrameSize(int)">maxWebsocketFrameSize</a></code>
then Vert.x will split it into multiple WebSocket frames before sending it on the wire.</p>
</div>
</div>
<div class="sect3">
<h4 id="_writing_frames_to_websockets">Writing frames to WebSockets</h4>
<div class="paragraph">
<p>A WebSocket message can be composed of multiple frames. In this case the first frame is either a <em>binary</em> or <em>text</em> frame
followed by zero or more <em>continuation</em> frames.</p>
</div>
<div class="paragraph">
<p>The last frame in the message is marked as <em>final</em>.</p>
</div>
<div class="paragraph">
<p>To send a message consisting of multiple frames you create frames using
<code><a href="../../ceylondoc/vertx-core//http/WebSocketFrame.object.html#binaryFrame(io.vertx.core.buffer.Buffer,%20boolean)">WebSocketFrame.binaryFrame</a></code>
, <code><a href="../../ceylondoc/vertx-core//http/WebSocketFrame.object.html#textFrame(java.lang.String,%20boolean)">WebSocketFrame.textFrame</a></code> or
<code><a href="../../ceylondoc/vertx-core//http/WebSocketFrame.object.html#continuationFrame(io.vertx.core.buffer.Buffer,%20boolean)">WebSocketFrame.continuationFrame</a></code> and write them
to the WebSocket using <code><a href="../../ceylondoc/vertx-core//http/WebSocket.type.html#writeFrame(io.vertx.core.http.WebSocketFrame)">writeFrame</a></code>.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s an example for binary frames:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">import io.vertx.ceylon.core.http { webSocketFrame }

...


value frame1 = webSocketFrame.binaryFrame(buffer1, false);
websocket.writeFrame(frame1);

value frame2 = webSocketFrame.continuationFrame(buffer2, false);
websocket.writeFrame(frame2);

// Write the final frame
value frame3 = webSocketFrame.continuationFrame(buffer2, true);
websocket.writeFrame(frame3);</code></pre>
</div>
</div>
<div class="paragraph">
<p>In many cases you just want to send a websocket message that consists of a single final frame, so we provide a couple
of shortcut methods to do that with <code><a href="../../ceylondoc/vertx-core//http/WebSocket.type.html#writeFinalBinaryFrame(io.vertx.core.buffer.Buffer)">writeFinalBinaryFrame</a></code>
and <code><a href="../../ceylondoc/vertx-core//http/WebSocket.type.html#writeFinalTextFrame(java.lang.String)">writeFinalTextFrame</a></code>.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s an example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">import io.vertx.ceylon.core.buffer { buffer }

...


// Send a websocket messages consisting of a single final text frame:

websocket.writeFinalTextFrame("Geronimo!");

// Send a websocket messages consisting of a single final binary frame:

value buff = buffer.buffer().appendInt(12).appendString("foo");

websocket.writeFinalBinaryFrame(buff);</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_reading_frames_from_websockets">Reading frames from WebSockets</h4>
<div class="paragraph">
<p>To read frames from a WebSocket you use the <code><a href="../../ceylondoc/vertx-core//http/WebSocket.type.html#frameHandler(io.vertx.core.Handler)">frameHandler</a></code>.</p>
</div>
<div class="paragraph">
<p>The frame handler will be called with instances of <code><a href="../../ceylondoc/vertx-core//http/WebSocketFrame.type.html">WebSocketFrame</a></code> when a frame arrives,
for example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">websocket.frameHandler((WebSocketFrame frame) {
  print("Received a frame of size!");
});</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_closing_websockets">Closing WebSockets</h4>
<div class="paragraph">
<p>Use <code><a href="../../ceylondoc/vertx-core//http/WebSocketBase.type.html#close()">close</a></code> to close the WebSocket connection when you have finished with it.</p>
</div>
</div>
<div class="sect3">
<h4 id="_streaming_websockets">Streaming WebSockets</h4>
<div class="paragraph">
<p>The <code><a href="../../ceylondoc/vertx-core//http/WebSocket.type.html">WebSocket</a></code> instance is also a <code><a href="../../ceylondoc/vertx-core//streams/ReadStream.type.html">ReadStream</a></code> and a
<code><a href="../../ceylondoc/vertx-core//streams/WriteStream.type.html">WriteStream</a></code> so it can be used with pumps.</p>
</div>
<div class="paragraph">
<p>When using a WebSocket as a write stream or a read stream it can only be used with WebSockets connections that are
used with binary frames that are no split over multiple frames.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_using_a_proxy_for_http_https_connections">Using a proxy for HTTP/HTTPS connections</h3>
<div class="paragraph">
<p>The http client supports accessing http/https URLs via a HTTP proxy (e.g. Squid) or <em>SOCKS4a</em> or <em>SOCKS5</em> proxy.
The CONNECT protocol uses HTTP/1.x but can connect to HTTP/1.x and HTTP/2 servers.</p>
</div>
<div class="paragraph">
<p>Connecting to h2c (unencrypted HTTP/2 servers) is likely not supported by http proxies since they will support
HTTP/1.1 only.</p>
</div>
<div class="paragraph">
<p>The proxy can be configured in the <code><a href="../../ceylondoc/vertx-core//http/HttpClientOptions.type.html">HttpClientOptions</a></code> by setting a
<code><a href="../../ceylondoc/vertx-core//net/ProxyOptions.type.html">ProxyOptions</a></code> object containing proxy type, hostname, port and optionally username and password.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s an example of using an HTTP proxy:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">import io.vertx.ceylon.core.net { http }

...


value options = HttpClientOptions {
  proxyOptions = ProxyOptions {
    type = "HTTP";
    host = "localhost";
    port = 3128;
    username = "username";
    password = "secret";
  };
};
value client = vertx.createHttpClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>When the client connects to an http URL, it connects to the proxy server and provides the full URL in the
HTTP request ("GET <a href="http://www.somehost.com/path/file.html" class="bare">http://www.somehost.com/path/file.html</a> HTTP/1.1").</p>
</div>
<div class="paragraph">
<p>When the client connects to an https URL, it asks the proxy to create a tunnel to the remote host with
the CONNECT method.</p>
</div>
<div class="paragraph">
<p>For a SOCKS5 proxy:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-ceylon" data-lang="ceylon">import io.vertx.ceylon.core.net { socks5 }

...


value options = HttpClientOptions {
  proxyOptions = ProxyOptions {
    type = "SOCKS5";
    host = "localhost";
    port = 1080;
    username = "username";
    password = "secret";
  };
};
value client = vertx.createHttpClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>The DNS resolution is always done on the proxy server, to achieve the functionality of a SOCKS4 client, it is necessary
to resolve the DNS address locally.</p>
</div>
</div>
<div class="sect2">
<h3 id="_automatic_clean_up_in_verticles">Automatic clean-up in verticles</h3>
<div class="paragraph">
<p>If you&#8217;re creating http servers and clients from inside verticles, those servers and clients will be automatically closed
when the verticle is undeployed.</p>
</div>
</div>
</div>
</div>

        

        
          <div id="footer">
            <div id="footer-text">
              
                Last updated 2016-09-12 08:38:04 CEST
              
              
            </div>
          </div>
        
      </div>
    </div>
  </div>
</div>

<footer>
  <div class="container">
    <div class="row">
      <div class="col-xs-6 col-sm-3 col-md-3 col-lg-2">
        <h2>Vert.x</h2>
        <ul class="list-unstyled">
          <li><a href="http://vertx.io/">Home</a></li>
          <li><a href="http://vertx.io/download/">Download</a></li>
          <li><a href="http://vertx.io/docs/">Documentation</a></li>
          <li><a href="https://github.com/vert-x3/wiki/wiki">Wiki</a></li>
          <li><a href="http://vertx.io/blog/">Blog</a></li>
          <li><a href="http://vertx.io/vertx2/" class="vertx-2-link">Vert.x 2</a></li>
        </ul>
      </div>
      <div class="col-xs-6 col-sm-3 col-md-3 col-lg-2">
        <h2>Community</h2>
        <ul class="list-unstyled">
          <li><a href="http://vertx.io/community/">Help &amp; Contributors</a></li>
          <li><a href="http://vertx.io/materials/">Learning materials</a></li>
          <li><a href="https://groups.google.com/forum/?fromgroups#!forum/vertx">User Group</a></li>
          <li><a href="https://groups.google.com/forum/?fromgroups#!forum/vertx-dev">Developer Group</a></li>
        </ul>
      </div>

      <div class="col-xs-12 col-sm-6 col-lg-offset-2 col-md-6 copyright">
        <p>Vert.x is open source and dual licensed under the <a href="https://www.eclipse.org/org/documents/epl-v10.php">Eclipse Public License 1.0</a> and <a href="https://www.apache.org/licenses/LICENSE-2.0.html">Apache License 2.0</a>.</p>
        <p>This website is licensed under the <a href="http://creativecommons.org/licenses/by-sa/3.0/">CC BY-SA 3.0 License</a>.<br>
        Design by <a href="http://www.michel-kraemer.com">Michel Kr&auml;mer</a>. <a href="http://www.entypo.com">Entypo pictograms</a> by Daniel Bruce.</p>
        <div class="row">
          <div class="col-xs-12 col-lg-offset-1 col-md-5">
            <a href="http://eclipse.org">
            <img class="logo eclipse-logo" src="http://vertx.io/assets/eclipse_logo_grey_small.png" width="204" height="48">
            </a>
          </div>
          <div class="col-xs-12 col-md-offset-2 col-lg-offset-0 col-md-5">
            <a href="http://cloudbees.com">
            <img class="logo cloudbees-logo" src="http://vertx.io/assets/Button-Built-on-CB-1-grey.png" width="180" height="48">
           </a>
          </div>
          <div class="col-xs-12 col-md-offset-2 col-lg-offset-1 col-md-5 jprofiler">
            <a href="http://www.ej-technologies.com/products/jprofiler/overview.html"
            style="text-decoration:none">
            <img class="logo jprofiler-logo" src="http://vertx.io/assets/jprofiler-logo.png" width="48" height="48"><span class="jprofiler-logo">&nbsp; JPROFILER</span>
            </a>
          </div>
        </div>
      </div>
    </div>
  </div>
</footer>

<script src="http://static.jboss.org/theme/js/libs/jquery/jquery-1.9.1.min.js"></script>
<script src="http://vertx.io/javascripts/bootstrap.min.js"></script>
<script src="http://vertx.io/javascripts/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>



<script src="http://vertx.io/javascripts/sidebar.js"></script>


</body>
</html>
